📅  最后修改于: 2023-12-03 15:24:14.117000             🧑  作者: Mango
在 JavaScript 中,我们可以使用内置的 Date
对象来获取日期和时间。如果我们只想要获取日期的月份和年份,我们可以使用以下方法。
我们可以通过创建一个新的 Date
对象并调用它的 getMonth()
和 getFullYear()
方法来获取当前月份和年份。这两个方法将返回一个数字,对应于月份(0 到 11)和年份(比如 2021)。
const today = new Date();
const month = today.getMonth();
const year = today.getFullYear();
我们可以获取任何给定日期的月份和年份,只需将该日期传递给 Date
对象的构造函数即可。
const date = new Date('2022-10-31');
const month = date.getMonth(); // 返回 9,对应于十月份
const year = date.getFullYear(); // 返回 2022
获取当前月份和年份的代码:
const today = new Date();
const month = today.getMonth();
const year = today.getFullYear();
获取特定日期的月份和年份的代码:
const date = new Date('2022-10-31');
const month = date.getMonth(); // 返回 9,对应于十月份
const year = date.getFullYear(); // 返回 2022
希望这篇文章能对你有所帮助!