JavaScript Date getMonth() 方法
getMonth() 方法是 JavaScript Date 对象的内置函数。它用于检索指定日期对象的月份部分,代表一年中的月份。返回值将为 0 到 11 之间的整数(其中 0 表示一年中的第一个月,11 表示最后一个月)。
如果提供的 Date 对象为无效日期,此方法将返回非数字 (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>
输出
正如我们在输出中看到的,月份部分已根据当地时间返回。
示例 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>
输出
根据世界标准时间返回月份名称。

