JavaScript getUTCMonth() 方法



JavaScript 的Date getUTCMonth() 方法不接受任何参数,将根据世界标准时间检索日期对象的月份分量。返回值将是一个 0 到 11 之间的整数(其中 0 表示一年的第一个月,11 表示最后一个月)。如果提供的 Date 对象无效,则此方法将返回NaN作为结果。

语法

以下是 JavaScript Date getUTCMonth() 方法的语法:

getUTCMonth();

此方法不接受任何参数。

返回值

此方法返回一个 0 到 11 之间的整数,表示世界标准时间的月份。

示例 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>

输出

这将返回 "9" 作为提供日期的月份值。(原文错误,10月应该返回9)

示例 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>

输出

它根据世界标准时间返回月份的名称。

广告
© . All rights reserved.