Date.prototype.getMonth()

Date 实例的 getMonth() 方法根据当地时间返回该日期的月份,作为从零开始的值(其中零表示一年中的第一个月)。

¥The getMonth() method of Date instances returns the month for this date according to local time, as a zero-based value (where zero indicates the first month of the year).

Try it

语法

¥Syntax

js
getMonth()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

0 到 11 之间的整数,表示给定日期根据当地时间的月份:0 代表一月,1 代表二月,依此类推。如果日期是 invalid,则返回 NaN

¥An integer, between 0 and 11, representing the month for the given date according to local time: 0 for January, 1 for February, and so on. Returns NaN if the date is invalid.

描述

¥Description

getMonth() 的返回值是从零开始的,这对于索引月份数组很有用,例如:

¥The return value of getMonth() is zero-based, which is useful for indexing into arrays of months, for example:

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

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

但是,出于国际化的目的,你应该更喜欢使用 Intl.DateTimeFormatoptions 参数。

¥However, for the purpose of internationalization, you should prefer using Intl.DateTimeFormat with the options parameter instead.

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"

示例

¥Examples

使用 getMonth()

¥Using getMonth()

基于 Date 对象 xmas95 的值,month 变量具有值 11

¥The month variable has value 11, based on the value of the Date object xmas95.

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

console.log(month); // 11

规范

Specification
ECMAScript Language Specification
# sec-date.prototype.getmonth

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看