Get month name from Date

我怎样才能从这个日期对象在JavaScript中生成月份的名称(例如:10月/ 10月)?

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

较短的版本:

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

It is now possible to do this with the ECMAScript Internationalization API:

var date = new Date("10/11/2009"),
    locale = "en-us",
    month = date.toLocaleString(locale, { month: "long" });

http://jsfiddle.net/dstorey/Xgerq/

"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.

You can change the locale to any that you please, and it will use the right name for that language/country.

With toLocaleString you have to pass in the locale and options each time. If you are going do use the same locale info and formatting options on multiple different dates, you can use Intl.DateTimeFormat instead:

var formatter = new Intl.DateTimeFormat("fr", { month: "short" }),
month1 = formatter.format(new Date()),
month2 = formatter.format(new Date(2003-05-12));

// sept. and déc.
console.log(month1 + " and " + month2);

The main issue with this API is it is new. It is only available in Blink browsers (Chrome and Opera), IE11, Microsoft Edge and Firefox 29+. It is not supported by Safari.

For more information see my blog post on the Internationalization 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: [...]};
链接地址: http://www.djcxy.com/p/36734.html

上一篇: 乔达:如何在两个日期之间获得数月和数天

下一篇: 从日期获取月份名称