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>

輸出

它根據世界標準時間返回月份的名稱。

廣告