简体   繁体   English

从日期中获取月份名称

[英]Get month name from Date

How can I generate the name of the month (eg: Oct/October) from this date object in JavaScript?如何从 JavaScript 中的日期 object 生成月份名称(例如:Oct/October)?

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

Shorter version:较短的版本:

 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()]);

Note (2019-03-08) - This answer by me which I originally wrote in 2009 is outdated.注意(2019-03-08) - 我最初在 2009 年写的这个答案已经过时了。 See David Storey's answer for a better solution.请参阅David Storey 的答案以获得更好的解决方案。

It is now possible to do this with the ECMAScript Internationalization API:现在可以使用 ECMAScript 国际化 API 来做到这一点:

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

'long' uses the full name of the month, 'short' for the short name, and 'narrow' for a more minimal version, such as the first letter in alphabetical languages. 'long'使用月份的全名, 'short'使用短名称, 'narrow'使用更小的版本,例如字母语言中的第一个字母。

You can change the locale from browser's 'default' to any that you please (eg 'en-us' ), and it will use the right name for that language/country.您可以将区域设置从浏览器的'default'更改为您喜欢的任何区域(例如'en-us' ),它将使用该语言/国家/地区的正确名称。

With toLocaleString api you have to pass in the locale and options each time.使用toLocaleString api,您每次都必须传入语言环境和选项。 If you are going do use the same locale info and formatting options on multiple different dates, you can use Intl.DateTimeFormat instead:如果您要在多个不同日期使用相同的语言环境信息和格式选项,您可以使用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".

For more information see my blog post on the Internationalization API .有关更多信息,请参阅我关于国际化 API 的博客文章。

Here's another one, with support for localization :)这是另一个,支持本地化:)

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']
    }
};

you can then easily add support for other languages:然后,您可以轻松添加对其他语言的支持:

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

I heartily recommend the format function from, the moment.js library, which you can use like this:我衷心推荐来自moment.js库的format函数,您可以像这样使用它:

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

Use "MMMM" instead of "MMM" if you need the full name of the month如果您需要月份的全名,请使用“MMMM”而不是“MMM”

In addition to a lengthy list of other features, it has strong support for internationalization .除了一长串的其他功能外,它还对国际化有很强的支持

If you don't mind extending the Date prototype (and there are some good reasons to not want to do this), you can actually come up with a very easy method:如果你不介意扩展 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"

These functions will then apply to all javascript Date objects.然后这些函数将应用于所有javascript Date 对象。

You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter您可以简单地使用 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'}));

You can find more information in the Firefox documentation您可以在 Firefox 文档中找到更多信息

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

It can be used as它可以用作

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

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

Some common easy process from date object can be done by this.可以通过此完成来自日期对象的一些常见的简单过程。

 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()))

Or you can make date prototype like或者你可以制作日期原型

 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())

Ex:前任:

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

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

You might use datejs to do that.您可以使用datejs来做到这一点。 Check the FormatSpecifiers , MMMM gives you the month's name:检查FormatSpecifiers ,MMMM 为您提供月份名称:

var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));

And datejs got that localized for more than 150 locales!而 datejs 已针对 150 多个语言环境进行了本地化! See here 看这里

Try:尝试:

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

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

格式化日期的另一种方法

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

Here's a way that does not depend on a hard-coded array and supports multiple locales.这是一种不依赖于硬编码数组并支持多种语言环境的方法。

If you need a whole array:如果你需要一个完整的数组:

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;
};

Usage:用法:

console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]

If you need only a selected month (faster):如果您只需要选定的月份(更快):

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

Usage:用法:

console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> февруари
console.log(monthLocalizedString(1, 'de')); // -> Februar

Tested and works fine on Chrome and IE 11. On mozilla some modifications are needed, because it returns the whole date.在 Chrome 和 IE 11 上测试并正常工作。在 mozilla 上需要一些修改,因为它返回整个日期。

Instead of declaring array which hold all the month name and then pointing with an index, we can also write it in a shorter version as below:除了声明包含所有月份名称然后指向索引的数组之外,我们还可以将其编写为较短的版本,如下所示:

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

Unfortunately the best way to extract the month name is from the UTCString representation:不幸的是,提取月份名称的最佳方法是从 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'

If you are in hurry...then here you go!如果你赶时间......那么你去吧!

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

Expected Output: "Apr"预期输出: "Apr"

You can use one of several available Date formatters.您可以使用几种可用的日期格式化程序之一。 Since this falls within the JavaScript specification, it will be available in both browser and server-side modes.由于这属于 JavaScript 规范,它将在浏览器和服务器端模式中可用。

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

eg例如

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

There are more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Datehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date还有更多

The natural format this days is to use Moment.js.现在的自然格式是使用 Moment.js。

The way to get the month in a string format , is very simple in Moment.js no need to hard code the month names in your code: To get the current month and year in month name format and full year (May 2015) :以字符串格式获取月份的方法在 Moment.js 中非常简单,无需在代码中对月份名称进行硬编码:以月份名称格式和全年(2015 年 5 月)获取当前月份和年份:

  moment(new Date).format("MMMM YYYY");

If we need to pass our input then we need to use the following way如果我们需要传递我们的输入,那么我们需要使用以下方式

input: '2020-12-28'输入: '2020-12-28'

Code:代码:

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

Output: "Dec 2020"输出: “2020 年 12 月”

Tested on IE 11, Chrome, Firefox在 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);

If you don't want to use an external library, or store an array of month names, or if the ECMAScript Internationalization API is not good enough because of browser compatibility you can always do it the old-fashioned way by extracting the info from the date output:如果您不想使用外部库,或存储月份名称数组,或者 ECMAScript 国际化 API 由于浏览器兼容性而不够好,您总是可以通过从日期输出:

var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);

This would give you the abbreviated month name, eg Oct. I believe the date will come in all sorts of formats depending on the initialization and your locale so take a look at what toDateString() returns and recalculate your substring() values based on that.这将为您提供缩写的月份名称,例如 Oct。我相信日期会根据初始化和您的语言环境以各种格式出现,因此请查看toDateString()返回的内容并基于此重新计算您的substring()值.

This can be also done if you are using kendo.如果您使用剑道,也可以这样做。

kendo.toString(dateobject, "MMMM");

Here are list of formatters from kendo site :以下是剑道网站的格式化程序列表:

"d" Renders the day of the month, from 1 through 31. "d" 渲染一个月中的第几天,从 1 到 31。

"dd" The day of the month, from 01 through 31. "dd" 一个月中的第几天,从 01 到 31。

"ddd" The abbreviated name of the day of the week. “ddd” 星期几的缩写名称。

"dddd" The full name of the day of the week. “dddd” 星期几的全名。

"f" The tenths of a second in a date and time value. "f" 日期和时间值中的十分之一秒。

"ff" The hundredths of a second in a date and time value. "ff" 日期和时间值中的百分之一秒。

"fff" The milliseconds in a date and time value. "fff" 日期和时间值中的毫秒数。

"M" The month, from 1 through 12. “M” 月份,从 1 到 12。

"MM" The month, from 01 through 12. “MM” 月份,从 01 到 12。

"MMM" The abbreviated name of the month. “MMM” 月份的缩写名称。

"MMMM" The full name of the month. “MMMM” 月份的全称。

"h" The hour, using a 12-hour clock from 1 to 12. "h" 小时,使用从 1 到 12 的 12 小时制。

"hh" The hour, using a 12-hour clock from 01 to 12. "hh" 小时,使用从 01 到 12 的 12 小时制。

"H" The hour, using a 24-hour clock from 1 to 23. "H" 小时,使用 24 小时制,从 1 到 23。

"HH" The hour, using a 24-hour clock from 01 to 23. “HH” 小时,使用从 01 到 23 的 24 小时制。

"m" The minute, from 0 through 59. "m" 分钟,从 0 到 59。

"mm" The minute, from 00 through 59. "mm" 分钟,从 00 到 59。

"s" The second, from 0 through 59. "s" 秒,从 0 到 59。

"ss" The second, from 00 through 59. "ss" 第二个,从 00 到 59。

"tt" The AM/PM designator. “tt” AM/PM 指示符。

"yy" The last two characters from the year value. “yy” 年份值的最后两个字符。

"yyyy" The year full value. "yyyy" 年份完整值。

"zzz" The local timezone when using formats to parse UTC date strings. "zzz" 使用格式解析 UTC 日期字符串时的本地时区。

You can handle with or without translating to the local language您可以在翻译或不翻译成当地语言的情况下进行处理

  1. Generates value as "11 Oct 2009"生成值“2009 年 10 月 11 日”

 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()) }

  1. The ECMAScript Internationalization API to translate month to local language (eg: 11 octobre)将月份翻译成当地语言的 ECMAScript 国际化 API(例如:11 octobre)

 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' })) }

You can try this:你可以试试这个:

 let d = new Date(), t = d.toDateString().split(" "); console.log(t[2] + " " + t[1] + " " + t[3]);

If you're using jQuery, you're probably also using jQuery UI, which means you can use $.datepicker.formatDate() .如果您使用 jQuery,那么您可能也在使用 jQuery UI,这意味着您可以使用$.datepicker.formatDate()

$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] );   // dutch
$.datepicker.formatDate( "dd MM yy", objDate );

My Best Solution is as follow:我的最佳解决方案如下:

       var dateValue = Date();
       var month = dateValue.substring(4,7);
       var date = dateValue.substring(8,10);
       var year = dateValue.substring(20,24);
       var finaldateString = date+"-"+month+"-"+year;

With momentjs , just use the format notation.使用momentjs ,只需使用格式符号。

const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August

For me this is best solution is,对我来说,这是最好的解决方案,

for TypeScript as well也适用于 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;
};

Output is输出是

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

也可以这样做:

var x = new Date().toString().split(' ')[1];    // "Jul"

Here's a function where you pass in 1 to 12, and returns back the full month name such as 'January' or 'July'这是一个 function,您可以在其中传递 1 到 12,然后返回完整的月份名称,例如“January”或“July”

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

If you don't want to use moment and want to display month name -如果您不想使用时刻并想显示月份名称 -

.config($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function(date) {      
      if(date !== null) {
        if(date.getMonthName == undefined) {
          date.getMonthName = function() {
            var monthNames = [ "January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December" ];
            return monthNames[this.getMonth()];
          }
        }        
        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();
        return day + ' ' + date.getMonthName() + ' ' + year;
      }
    };
  }

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

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

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

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

The easiest and simplest way.最简单和最简单的方法。

 //Basically converting whole date to string = "Fri Apr 2020' //then splitting by ' ' a space = ['Fri' 'Apr' '2020'] //then selecting second element of array = ['Fri' 'Apr' '2020'].[1] = 'Apr' var now = new Date(); var currentMonth = now.toDateString().split(' ')[1]; console.log(currentMonth);

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

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

Just extending on the many other excellent answers - if you are using jQuery - you could just do something like 只是扩展许多其他出色的答案-如果您使用的是jQuery-您可以做类似的事情

$.fn.getMonthName = function(date) {

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

    return monthNames[date.getMonth()];

};

where date is equal to the var d = new Date(somevalue) . 其中date等于var d = new Date(somevalue) The primary advantage of this is per @nickf said about avoiding the global namespace. 每个@nickf所说的主要优点是避免全局名称空间。

To get a array of month name : 要获取月份名称数组:

Date.monthNames = function( ) {
var arrMonth = [],
    dateRef = new Date(),
    year = dateRef.getFullYear();

dateRef.setMonth(0);
while (year == dateRef.getFullYear()) {
    /* push le mois en lettre et passe au mois suivant */
    arrMonth.push( (dateRef.toLocaleString().split(' '))[2] );
    dateRef.setMonth( dateRef.getMonth() + 1);
}

return arrMonth;
}

alert(Date.monthNames().toString());

// -> janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre

http://jsfiddle.net/polinux/qb346/ http://jsfiddle.net/polinux/qb346/

Just write a simple wrapper around toLocaleString : 只需在toLocaleString周围编写一个简单的包装即可:

 function LocalDate(locale) { this.locale = locale; } LocalDate.prototype.getMonthName = function(date) { return date.toLocaleString(this.locale,{month:"long"}); }; var objDate = new Date("10/11/2009"); var localDate = new LocalDate("en"); console.log(localDate.getMonthName(objDate)); localDate.locale = "ru"; console.log(localDate.getMonthName(objDate)); localDate.locale = "zh"; console.log(localDate.getMonthName(objDate)); 

A quick hack I used which works well: 我使用的一个快速技巧很有效:

 const monthNumber = 8; const yearNumber = 2018; const date = `${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1] } ${yearNumber}`; console.log(date); 

I did it via DatePipe.我是通过 DatePipe 完成的。

const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');

You can inject the default locale inside your constructor like this:您可以像这样在构造函数中注入默认语言环境:

constructor(@Inject(LOCALE_ID) private locale: string){}

Reference from Angular https://angular.io/api/common/DatePipe来自 Angular https://angular.io/api/common/DatePipe的参考

Keep it simple: 把事情简单化:

echo date("d M Y");

which will give 这将给

31 Aug 2019

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM