从日期中获取月份名称

1007

在JavaScript中,我该如何从这个日期对象生成月份的名称(例如:Oct/October)?

var objDate = new Date("10/11/2009");

8
如果https://dev59.com/znI-5IYBdhLWcg3w18Z3#18648314可以被采纳,将有助于引导未来的读者得到更好的答案。 - Boghyon Hoffmann
41个回答

1487

现在可以使用ECMAScript国际化API来实现这一点:

const date = new Date(2009, 10, 10);  // 2009-11-10
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);

'long'使用月份的全名,'short'使用月份的缩写名称,'narrow'使用最简版本,例如在字母语言中使用第一个字母。

您可以将浏览器的区域设置从 'default' 更改为任何您喜欢的设置(例如 'en-us'),它将使用该语言/国家的正确名称。

使用 toLocaleStringapi 每次都需要传递地区设置和选项。如果您要在多个不同日期上使用相同的区域设置和格式选项,则可以使用 Intl.DateTimeFormat

const formatter = new Intl.DateTimeFormat('fr', { month: 'short' });
const month1 = formatter.format(new Date());
const month2 = formatter.format(new Date(2003, 5, 12));
console.log(`${month1} and ${month2}`); // current month in French and "juin".

欲了解更多信息,请参阅我的博客文章:国际化API


1
我可以确认Safari技术预览版支持此功能。我认为这应该是被接受的答案。 - Salman Hasrat Khan
7
很好的解决方案,但对于我的使用情况来说,这种方法最终变得太慢了。我正在处理几百个项目,获取月份和年份平均需要约1毫秒(在Chrome和Safari中)。最终我选择了被接受的答案,因为它表现得更好。如果只需要调用几次,这将是我的首选方法。 - t.888
9
现在大多数浏览器都支持这个功能:https://caniuse.com/#search=intl - eyal83
9
有关React Native的说明,这适用于iOS设备,但在Android上显示不正确(只是输出完整的时间戳)。 - hardanger
2
请注意,这在任何版本的IE上都不起作用(对于所有企业客户)。 - bsplosion
显示剩余6条评论

1473

简短版本:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);

(2019-03-08)- 我于2009年撰写的此答案已经过时。请查看David Storey的答案,以获得更好的解决方案。


465
有点令人沮丧的是,即使 new Date() 返回 Tue Sep 06 2011 20:02:25 GMT+0200 (CEST) 这明显说明日期对象已经内部定义了所有这些内容(月份和星期几的名称),但它并不是公开的,所以我们需要再次输入所有内容。 :((说明:本翻译保持原文意思,简化语言表达,并未添加解释或其他额外内容) - zanona
9
若需要为每种语言支持的月份名称做翻译,则这不是一个理想的解决方案。使用 String#splittoStringtoDateString 必有更好的方式。 - rxgx
24
多种语言 = 多维数组 ;) translations["monthName"][currentLanguage][d.getMonth()] - nuala
29
@zanona,一个日期对象并不一定有"所有这些内部定义"。在ECMA-262中所需的仅是时间值,即一个数字。你看到的是Date.prototype.toString的结果,这是实现相关的。 - RobG
9
@Devin 但这样每次访问数组时都会重新分配内存。 - Cole Tobin
显示剩余10条评论

174

这里还有一个支持本地化的版本 :)

Date.prototype.getMonthName = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names[this.getMonth()];
};

Date.prototype.getMonthNameShort = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names_short[this.getMonth()];
};

Date.locale = {
    en: {
       month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
       month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    }
};

你可以轻松地添加对其他语言的支持:

Date.locale.fr = {month_names: [...]};

2
注意:自6.x版本起,此代码在Node上无法运行,因为Date.locale是未定义的。但对于其他JS实现来说,这是一个非常好的答案! - mikemaccana
如果本地化名称数组是使用Date.prototype.toLocaleString构建的,那么这可能是有意义的。此外,扩展内置原型和对象并不被认为是一个好主意。 - RobG

83

如果我们需要传入输入,则需要使用以下方式

输入: '2020-12-28'

代码:

new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})

输出:"2020年12月"


1
非常好,这对我的情况完美地起作用了。谢谢! - 4uroraskye
我们可以使用用户本地代码而不是 'en-us' 吗? - vinalti
3
干净的解决方案。我只是添加了 day: 'numeric' - Rolly

77

我强烈推荐使用format函数,它来自于moment.js库,您可以像这样使用:

moment().format("MMM");  // "Apr" - current date
moment(new Date(2012, 01, 04)).format("MMM");  // "Feb" - from a local date
moment.utc(new Date(2012, 00, 04).format("MMM"); // "Jan" - from a UTC date

如果您需要月份的全名,请使用“MMMM”而不是“MMM”

除了其他众多功能外,它还具有强大的国际化支持


3
第一个选项将产生“Apr”。如果您想要完整的月份名称,请使用“MMMM”而不是“MMM”,因为“MMM”显示月份的前三个字母。请查看它们的文档获取帮助。 - Tomnar
如果你要走重度优化和减少HTTP请求的路线,这可能不适合你。相反,如果你只需要在一行代码中格式化月份名称,那么最好使用一个月份名称数组。 - OzzyTheGiant
5
Moment是一个非常庞大的库,对于这个需求来说太过繁琐。现代的替代方案包括Luxondate-fns,但是现在国际化API已经有了广泛的浏览器支持。 - Dan Dascalescu
1
moment.js已经被弃用,请参见https://github.com/you-dont-need/You-Dont-Need-Momentjs。 - GorvGoyl

66

如果您不介意扩展日期原型(但有一些好的理由不希望这样做),实际上您可以想出一个非常简单的方法:

Date.prototype.monthNames = [
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September",
    "October", "November", "December"
];

Date.prototype.getMonthName = function() {
    return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
    return this.getMonthName().substr(0, 3);
};

// usage:
var d = new Date();
alert(d.getMonthName());      // "October"
alert(d.getShortMonthName()); // "Oct"

这些函数将适用于所有JavaScript日期对象。


6
好的,需要翻译的内容是:"and there are some good reasons to not want to do this". 您好奇的是哪些理由? - KooiInc
15
因为你基本上是在全局空间中工作。如果导入别人的函数或库也执行此操作,则它们可能会相互覆盖。 - nickf

45

如果您匆忙...那么这里就是您需要的!

const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}

期望输出:"Apr"


37

您可以直接使用Date.toLocaleDateString()方法,并将需要解析的日期作为参数传递

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

const options = {  year: 'numeric', month: 'short', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('en-US', options));
// US format 


// In case you only want the month
console.log(event.toLocaleDateString(undefined, { month: 'short'}));
console.log(event.toLocaleDateString(undefined, { month: 'long'}));

您可以在火狐文档中找到更多信息。


25
Date.prototype.getMonthName = function() {
    var monthNames = [ "January", "February", "March", "April", "May", "June", 
                       "July", "August", "September", "October", "November", "December" ];
    return monthNames[this.getMonth()];
}

它可以被用作

var month_Name = new Date().getMonthName();

24

document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))


2021年11月4日 下午3:30:45 - Nadav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接