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
语法
参数
返回值
描述
¥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.DateTimeFormat
和 options
参数。
¥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"
示例
使用 getMonth()
规范
Specification |
---|
ECMAScript Language Specification # sec-date.prototype.getmonth |
浏览器兼容性
BCD tables only load in the browser