从日期获取月份名称

Shy*_*yju 624 javascript date date-format time-format

如何在JavaScript中从此日期对象生成月份名称(例如:10月/ 10月)?

var objDate = new Date("10/11/2009");
Run Code Online (Sandbox Code Playgroud)

Jes*_*per 1059

更短的版本:

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()]);
Run Code Online (Sandbox Code Playgroud)

  • 甚至让'new Date()`返回`Tue Sep 06 2011 20:02:25 GMT + 0200(CEST)`这显然意味着Date对象已经内部定义了所有这些(月和周日名称),这有点令人沮丧)它不公开,所以我们必须再次输入.:( (380认同)
  • @ zanona-日期对象不一定具有"所有内部定义的".ECMA-262中要求的只是[时间值](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1),这是一个数字.您所看到的是[*Date.prototype.toString*](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.2)的结果,它取决于实现. (25认同)
  • 多种语言=多维数组;)翻译["monthName"] [currentLanguage] [d.getMonth()] (23认同)
  • 如果必须为每种支持的语言包含月份名称,则不是理想的解决方案.使用`toString`或`toDateString`的`String#split`必须有更好的方法. (9认同)
  • @Devin但每次要访问它时都会重新分配数组. (9认同)
  • @RegencySoftware是的,但请注意`Date.getMonth()`也是从零开始的(它在几个月内返回0-11而不是1-12,这对人类更合乎逻辑). (3认同)
  • 或者只是 `'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')[new Date().getMonth()]` (2认同)
  • 这已经过时了,请改用David Storey提供的`toLocaleString`解决方案 (2认同)

Dav*_*rey 657

现在可以使用ECMAScript Internationalization API执行此操作:

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

'long'使用月份的全名,'short'短名称和'narrow'更小的版本,例如字母语言的第一个字母.

您可以将语言环境更改'default'为任何您喜欢的语言环境,并使用该语言/国家/地区的正确名称.

随着'en-us'你在区域设置和选项,每次通过.如果您要在多个不同日期使用相同的区域设置信息和格式选项,则可以使用toLocaleString:

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".
Run Code Online (Sandbox Code Playgroud)

这个API的主要问题是它是新的.它仅适用于Blink浏览器(Chrome和Opera),IE11,Microsoft Edge,Firefox 29+和Safari 10+

有关更多信息,请参阅我在国际化API上的博客文章.

  • 现在大多数浏览器都支持此功能:https://caniuse.com/#search=intl (7认同)
  • 请注意 React Native,这适用于 iOS 设备,但在 Android 上,它显示不正确(只是吐出整个时间戳)。 (6认同)
  • 很好的解决方案,但对于我的用例,这最终太慢了.我正在处理数百件物品,每件物品平均约1毫秒,以获得月份和年份(铬,野生动物园).我最终使用了接受的答案,但仅仅因为它表现得更好.如果我只需要调用几次,这将是我的首选方法. (4认同)
  • 请注意,这不适用于任何版本的 IE(对于拥有企业客户端的每个人)。 (2认同)

krc*_*cko 159

这是另一个,支持本地化:)

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']
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以轻松添加对其他语言的支持:

Date.locale.fr = {month_names: [...]};
Run Code Online (Sandbox Code Playgroud)

  • 注意**这对于6.x的节点**不起作用,因为`Date.locale`是`undefined`.这对于其他JS实现来说是一个很好的答案! (2认同)

nic*_*ckf 62

如果你不介意扩展Date原型(并且有一些很好的理由不想这样做),你实际上可以想出一个非常简单的方法:

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"
Run Code Online (Sandbox Code Playgroud)

然后,这些函数将应用于所有 javascript Date对象.

  • @Kooilnc:这是因为你基本上是在全球范围内工作.如果您导入其他人的功能或库也执行此操作,那么它们可能会相互覆盖. (13认同)
  • "并且有一些很好的理由不想这样做".只是好奇:你的意思是什么原因? (6认同)

Bri*_*unt 59

我衷心推荐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
Run Code Online (Sandbox Code Playgroud)

除了冗长的其他功能列表外,它还强有力地支持国际化.

  • Moment是一个[非常](https://github.com/moment/moment/issues/3376)大型图书馆,对此有些过分了。现代的替代方案包括`Luxon`和`date-fns`,但是现在,[现在对[国际化API]有了广泛的浏览器支持](/sf/ask/115032431/ date#comment86944935_18648314)。 (3认同)
  • 第一个将导致“ Apr”。“ MMM”显示该月的前三个字母,如果要全名,请使用“ MMMM”。请参阅他们的[documentation](http://momentjs.com/docs/#/displaying/format/)以获得帮助。 (2认同)

And*_*aul 25

您可以简单地使用 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'}));
Run Code Online (Sandbox Code Playgroud)

您可以在 Firefox文档中找到更多信息


Azi*_*ark 22

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


Bee*_*tty 21

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

它可以用作

var month_Name = new Date().getMonthName();
Run Code Online (Sandbox Code Playgroud)


Tim*_*the 17

你可以使用datejs来做到这一点.检查FormatSpecifiers,MMMM为您提供月份名称:

var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
Run Code Online (Sandbox Code Playgroud)

而且datejs已经为超过150种语言环境进行了本地化!看这里


M.A*_*pon 17

这可以通过日期对象完成一些常见的简单过程.

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

function dateFormat1(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear();
}

function dateFormat2(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();
}

console.log(dateFormat1(new Date()))
console.log(dateFormat2(new Date()))
Run Code Online (Sandbox Code Playgroud)

或者你可以制作日期原型

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


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


console.log(new Date().getMonthName())
console.log(new Date().getFormatDate())
Run Code Online (Sandbox Code Playgroud)

例如:

var dateFormat3 = new Date().getMonthName(); # March

var dateFormat4 = new Date().getFormatDate(); # 16 March, 2017

  • 谢谢!我还不了解原型,但我很期待尝试一下. (2认同)

ven*_*668 15

格式化日期的另一种方法

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"
Run Code Online (Sandbox Code Playgroud)


Bay*_*ram 13

最简单、最简单的方法:

const dateStr = new Date(2020, 03, 10).toDateString(); // 'Fri Apr 10 2020'
const dateStrArr = dateStr.split(' '); // ['Fri', 'Apr', '10', '2020']
console.log(dateStrArr[1]); // 'Apr'
Run Code Online (Sandbox Code Playgroud)

  1. 将日期转换为字符串。
  2. 用 ' ' 空格分隔。
  3. 从数组中选择第二个元素。


小智 12

尝试:

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

var strDate =
    objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
    objDate.toLocaleString("en", { month: "long"  }) + ' ' +
    objDate.toLocaleString("en", { year: "numeric"});
Run Code Online (Sandbox Code Playgroud)


Дам*_*чев 9

这是一种不依赖于硬编码阵列并支持多种语言环境的方法.

如果你需要一个完整的数组:

var monthsLocalizedArray = function(locale) {
    var result = [];
    for(var i = 0; i < 12; i++) {
        result.push(new Date(2010,i).toLocaleString(locale,{month:"long"}));
    }
    return result;
};
Run Code Online (Sandbox Code Playgroud)

用法:

console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["??????", "????????", "????", "?????", "???", "???", "???", "??????", "?????????", "????????", "???????", "????????"]
Run Code Online (Sandbox Code Playgroud)

如果您只需要选定的月份(更快):

var monthLocalizedString = function(month, locale) {
    return new Date(2010,month).toLocaleString(locale,{month:"long"});
};
Run Code Online (Sandbox Code Playgroud)

用法:

console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> ????????
console.log(monthLocalizedString(1, 'de')); // -> Februar
Run Code Online (Sandbox Code Playgroud)

测试并在Chrome和IE 11上正常工作.在Mozilla上需要进行一些修改,因为它返回整个日期.


Zoe*_*e L 9

快捷方便

new Date("10/11/2009").toLocaleString("en-US", { month: "long" })
// 'October'
Run Code Online (Sandbox Code Playgroud)


Aar*_*nin 8

不幸的是,提取月份名称的最佳方法是来自UTCString表示:

Date.prototype.monthName = function() {
    return this.toUTCString().split(' ')[2]
};

d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)

d.monthName();
//=> 'Mar'
Run Code Online (Sandbox Code Playgroud)


小智 8

我们也可以用更短的版本来编写它,而不是声明包含所有月份名称然后用索引指向的数组:

var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
Run Code Online (Sandbox Code Playgroud)


sha*_*sol 7

今天的自然格式是使用Moment.js.

以字符串格式获取月份的方法在Moment.js中非常简单,无需在代码中对月份名称进行硬编码:获取当月和年份的名称格式和全年(2015年5月):

  moment(new Date).format("MMMM YYYY");
Run Code Online (Sandbox Code Playgroud)


Din*_*esh 6

您可以使用几种可用的日期格式化程序之一.由于这属于JavaScript规范,因此它将在浏览器和服务器端模式下可用.

objDate.toString().split(" ")[1]; // gives short name, unsure about locale 
objDate.toLocaleDateString.split(" ")[0]; // gives long name
Run Code Online (Sandbox Code Playgroud)

例如

js> objDate = new Date(new Date() - 9876543210)
Mon Feb 04 2013 12:37:09 GMT-0800 (PST)
js> objDate.toString().split(" ")[1]
Feb
js> objDate.toLocaleString().split(" ")[0]
February
Run Code Online (Sandbox Code Playgroud)

还有更多内容,访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


nav*_*ule 6

在 IE 11、Chrome、Firefox 上测试

const dt = new Date();
const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language;
const fullMonth = dt.toLocaleDateString(locale, {month: 'long'});
console.log(fullMonth);
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以试试这个:

let d = new Date(),
  t = d.toDateString().split(" ");

console.log(t[2] + " " + t[1] + " " + t[3]);
Run Code Online (Sandbox Code Playgroud)


Mit*_*shu 6

如果你赶时间......那么你去吧!

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

预期输出: "Apr"


Nav*_*dar 5

如果您使用剑道,也可以这样做。

kendo.toString(dateobject, "MMMM");
Run Code Online (Sandbox Code Playgroud)

以下是来自kendo 网站的格式化程序列表:

“d” 呈现该月中的第几天,从 1 到 31。

“dd” 一个月中的哪一天,从 01 到 31。

“ddd” 星期几的缩写名称。

“dddd” 星期几的全名。

“f” 日期和时间值中的十分之一秒。

“ff” 日期和时间值中的百分之一秒。

“fff” 日期和时间值中的毫秒。

“M” 月份,从 1 到 12。

“MM” 月份,从 01 到 12。

“MMM” 月份的缩写名称。

“MMMM” 月份的全名。

“h” 小时,使用 12 小时制,从 1 到 12。

“hh” 小时,使用 12 小时制,从 01 到 12。

“H” 小时,采用 24 小时制,从 1 点到 23 点。

“HH” 小时,使用 24 小时制,从 01 到 23。

“m” 分钟,从 0 到 59。

“mm” 分钟,从 00 到 59。

“s” 第二个,从 0 到 59。

“ss” 第二个,从 00 到 59。

“tt”AM/PM 指示符。

“yy” 年份值的最后两个字符。

“yyyy” 年份完整值。

"zzz" 使用格式解析 UTC 日期字符串时的本地时区。


小智 5

对我来说这是最好的解决方案是,

对于 TypeScript 也是如此

const env = process.env.REACT_APP_LOCALE || 'en';

const namedMonthsArray = (index?: number): string[] | string => {
  const months = [];

  for (let month = 0; month <= 11; month++) {
    months.push(
      new Date(new Date('1970-01-01').setMonth(month))
        .toLocaleString(env, {
          month: 'long',
        })
        .toString(),
    );
  }
  if (index) {
    return months[index];
  }
  return months;
};
Run Code Online (Sandbox Code Playgroud)

输出是

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Run Code Online (Sandbox Code Playgroud)


Pra*_*han 5

您可以翻译或不翻译为当地语言

  1. 生成值“11 Oct 2009”

const objDate = new Date("10/11/2009");
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
if (objDate !== 'Invalid Date' && !isNaN(objDate)) {
  console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())
}
Run Code Online (Sandbox Code Playgroud)

  1. ECMAScript 国际化 API 将月份翻译为本地语言(例如:10 月 11 日)

const convertDate = new Date('10/11/2009')
const lang = 'fr' // de, es, ch 
if (convertDate !== 'Invalid Date' && !isNaN(convertDate)) {
  console.log(convertDate.getDate() + ' ' + convertDate.toLocaleString(lang, {
    month: 'long'
  }))
}
Run Code Online (Sandbox Code Playgroud)


小智 5

也可以按如下方式完成:

var x = new Date().toString().split(' ')[1];    // "Jul"
Run Code Online (Sandbox Code Playgroud)


KAR*_*N.A 5

如果我们需要传递我们的输入,那么我们需要使用以下方式

输入: '2020-12-28'

代码:

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

输出: “2020 年 12 月”

  • 干净的解决方案。我刚刚添加了 `day: 'numeric'` (3认同)

zum*_*ard 5

这是一个函数,您传入 1 到 12,然后返回完整的月份名称,例如“January”或“July”

    function getMonthName(monthNumber) {
      return new Date('1999-' + monthNumber + '-15').toLocaleString('en-us', { month: 'long' })
    }
Run Code Online (Sandbox Code Playgroud)