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

浏览器兼容性

另见