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