从日期获取月份名称

JavaScript

YLD

2020-03-11

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

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

第766篇《从日期获取月份名称》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

19个回答
神乐 2020.03.11

Keep it simple:

echo date("d M Y");

which will give

31 Aug 2019
さ恋旧る 2020.03.11

Just write a simple wrapper around 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));

逆天古一Mandy 2020.03.11

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/

小哥达蒙 2020.03.11

I have a partial solution that I came up with. It uses a regular expression to extract the month and day name. But as I look through the Region and Language options (Windows) I realize that different cultures have different format order... maybe a better regular expression pattern could be useful.

function testDateInfo() {
        var months = new Array();
        var days = new Array();
        var workingDate = new Date();
        workingDate.setHours(0, 0, 0, 0);
        workingDate.setDate(1);
        var RE = new RegExp("([a-z]+)","ig");
        //-- get day names 0-6
        for (var i = 0; i < 7; i++) {

            var day = workingDate.getDay();
            //-- will eventually be in order
            if (days[day] == undefined)
                days[day] = workingDate.toLocaleDateString().match(RE)[0];
            workingDate.setDate(workingDate.getDate() + 1);
        }
        //--get month names 0-11
        for (var i = 0; i < 12; i++) {
            workingDate.setMonth(i);
            months.push(workingDate.toLocaleDateString().match(RE)[1]);
        }
        alert(days.join(",") + " \n\r " + months.join(","));
    }
Me无敌小哥 2020.03.11

Just extending on the many other excellent answers - if you are using jQuery - you could just do something like

$.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). The primary advantage of this is per @nickf said about avoiding the global namespace.

神无十三 2020.03.11

Store the names in a array and look up by the index of the month.

var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";

document.write("The current month is " + month[d.getMonth()]);

JavaScript getMonth() Method

Gil米亚卡卡西 2020.03.11

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.

"dd" The day of the month, from 01 through 31.

"ddd" The abbreviated name of the day of the week.

"dddd" The full name of the day of the week.

"f" The tenths of a second in a date and time value.

"ff" The hundredths of a second in a date and time value.

"fff" The milliseconds in a date and time value.

"M" The month, from 1 through 12.

"MM" The month, from 01 through 12.

"MMM" The abbreviated name of the month.

"MMMM" The full name of the month.

"h" The hour, using a 12-hour clock from 1 to 12.

"hh" The hour, using a 12-hour clock from 01 to 12.

"H" The hour, using a 24-hour clock from 1 to 23.

"HH" The hour, using a 24-hour clock from 01 to 23.

"m" The minute, from 0 through 59.

"mm" The minute, from 00 through 59.

"s" The second, from 0 through 59.

"ss" The second, from 00 through 59.

"tt" The AM/PM designator.

"yy" The last two characters from the year value.

"yyyy" The year full value.

"zzz" The local timezone when using formats to parse UTC date strings.

宝儿逆天 2020.03.11

如果您不想使用外部库或存储月份名称数组,或者由于浏览器兼容而导致ECMAScript国际化API不够好,那么您始终可以通过从日期输出:

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

这将为您提供缩写的月份名称,例如,十月。我相信日期会以各种格式出现,具体取决于初始化和您的语言环境,因此请查看toDateString()返回的内容并substring()根据该值重新计算值。

Eva西里蛋蛋 2020.03.11

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;
理查德阿飞 2020.03.11

如果您使用的是jQuery,则可能还使用了jQuery UI,这意味着您可以使用$ .datepicker.formatDate()

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

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

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

例如

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

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date中有更多内容

JinJinGil 2020.03.11

目前的自然格式是使用Moment.js。

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

  moment(new Date).format("MMMM YYYY");
斯丁西门 2020.03.11

除了声明包含所有月份名称的数组然后再指向索引之外,我们还可以将其编写为较短的版本,如下所示:

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

尝试:

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

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

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

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

datejs可以在150多个语言环境中进行本地化!看这里

Stafan泡芙 2020.03.11

我衷心推荐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”

除了冗长的其他功能列表,它还对国际化提供了强大的支持

神乐前端 2020.03.11
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();
伽罗Mandy 2020.03.11

如果您不介意扩展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"

这些功能随后将应用于所有 javascript Date对象。

GreenTonyL 2020.03.11

较短的版本:

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的答案以获得更好的解决方案。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android