JavaScript 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>

輸出

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

廣告