Date.getMonth()方法是 JavaScript 的 Date 对象中的内置函数。它检索指定 date 对象的 month 组件,表示一年中的月份。返回值将是介于 0 到 11 之间的整数(其中 0 表示一年的第一个月,11 表示最后一个月)。
如果提供的 Date 对象是无效日期,则此方法将返回 Not a Number (NaN) 作为结果。
语法
以下是 JavaScript Date.getMonth() 方法的语法 -
getMonth();
此方法不接受任何参数。
返回值
此方法返回一个整数,该整数表示指定日期对象的月份。
示例 1
在下面的示例中,我们使用 JavaScript Date.getMonth() 方法从日期中检索月份组件 -
<html>
<body>
<script>
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
document.write(currentMonth);
</script>
</body>
</html>
输出
正如我们所看到的,month 组件已根据本地时间返回。
示例 2
在此示例中,我们将打印指定日期值的分钟值 -
<html>
<body>
<script>
const specificDate = new Date('2023-11-25');
const monthOfDate = specificDate.getMonth();
document.write(monthOfDate);
</script>
</body>
</html>
输出
这将返回 “10” 作为所提供日期的月份值。
示例 3
在这里,我们通过函数检索当前月份的名称 -
<html>
<body>
<script>
function getMonthName(date) {
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[date.getMonth()];
}
const currentDate = new Date();
const currentMonthName = getMonthName(currentDate);
document.write(currentMonthName);
</script>
</body>
</html>
输出
它根据世界时返回月份的名称。