Date.prototype.getMonth()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

getMonth() 方法用於 Date 物件,根據本地時間返回該日期月份,返回值為零基數 (0 表示一年中的第一個月)。

試一試

const moonLanding = new Date("July 20, 69 00:20:18");

console.log(moonLanding.getMonth()); // (January gives 0)
// Expected output: 6

語法

js
getMonth()

引數

無。

返回值

返回一個整數,介於 0 和 11 之間,表示根據本地時間給定的日期的月份:0 表示一月,1 表示二月,以此類推。如果日期 無效,則返回 NaN

描述

getMonth() 的返回值是零基數的,這在為月份陣列建立索引時非常有用,例如:

js
const valentines = new Date("1995-02-14");
const month = valentines.getMonth();
const monthNames = ["January", "February", "March" /* , … */];

console.log(monthNames[month]); // "February"

但是,為了實現國際化,您應該優先使用帶有 options 引數的 Intl.DateTimeFormat

js
const options = { month: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(valentines));
// "February"
console.log(new Intl.DateTimeFormat("de-DE", options).format(valentines));
// "Februar"

示例

使用 getMonth()

month 變數的值為 11,這是基於 Date 物件 xmas95 的值。

js
const xmas95 = new Date("1995-12-25T23:15:30");
const month = xmas95.getMonth();

console.log(month); // 11

規範

規範
ECMAScript® 2026 語言規範
# sec-date.prototype.getmonth

瀏覽器相容性

另見