关于javascript:从日期获取月份名称

Get month name from Date

如何用javascript从这个日期对象生成月份名称(例如:十月/十月)?

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


较短版本:

1
2
3
4
5
6
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的答案以获得更好的解决方案。


现在可以使用EcmaScript国际化API执行此操作:

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

long使用本月的全名,short用于简称,narrow用于更精简的版本,如字母语言中的第一个字母。

您可以将区域设置从en-us更改为任何您想要的,它将使用该语言/国家的正确名称。

使用toLocaleString时,每次都必须传递区域和选项。如果要在多个不同的日期上使用相同的区域设置信息和格式选项,则可以使用Intl.DateTimeFormat

1
2
3
4
5
6
7
8
9
10
11
if (typeof Intl == 'object' && typeof Intl.DateTimeFormat == 'function') {
  var formatter = new Intl.DateTimeFormat("fr", {
      month:"short"
    }),
    month1 = formatter.format(new Date()),
    month2 = formatter.format(new Date(2003, 5, 12));

  // current month in French and"juin".
  console.log(month1 +" and" + month2);
 
}

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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']
    }
};

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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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日期对象。


我衷心推荐moment.js库中的format函数,您可以这样使用:

1
2
3
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"

除了冗长的其他特性列表外,它还对国际化提供了强有力的支持。


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

它可以用作

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

你可以用datejs来完成。检查格式说明符,mmmm给出月份名称:

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

而datejs的本地化范围超过了150个地区!看到这里


一些常见的从日期对象开始的简单过程可以通过这个来完成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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()))

或者你可以把日期原型做成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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())

前任:

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

江户十一〔4〕江户十一〔5〕号


尝试:

1
2
3
4
5
6
var objDate = new Date("10/11/2009");

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


这是一种不依赖硬编码数组并支持多个区域设置的方法。

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

1
2
3
4
5
6
7
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;
};

用途:

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

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

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

用途:

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

经过测试,在Chrome和IE 11上运行良好。在Mozilla上需要一些修改,因为它返回整个日期。


现在的自然格式是使用moment.js。

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

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


不幸的是,从utcstring表示中提取月份名称的最佳方法是:

1
2
3
4
5
6
7
8
9
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'

我们不需要声明包含所有月份名称的数组,而是用一个索引来指向它,我们还可以用下面的较短版本来编写它:

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


您可以使用几种可用的日期格式设置工具之一。因为这属于javascript规范,所以它在浏览器和服务器端模式下都可用。

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

例如

1
2
3
4
5
6
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/en-us/docs/web/javascript/reference/global_objects/date。


对于momentjs,只需使用格式符号。

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


如果您使用的是jquery,那么您可能还使用jquery UI,这意味着您可以使用$.datepicker.formatDate()。

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

将名称存储在数组中并按月份索引查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()方法


如果您不想使用外部库,或存储月份名称数组,或者如果由于浏览器兼容性,EcmaScript国际化API不够好,则可以通过从日期输出中提取信息的老式方法来执行此操作:

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

这将给您一个缩写的月份名称,例如OCT。我相信根据初始化和您的区域设置,日期将以各种格式出现,因此请查看toDateString()返回的内容,并基于该内容重新计算substring()值。


我的最佳解决方案如下:

1
2
3
4
5
       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;


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

1
kendo.toString(dateobject,"MMMM");

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

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


如果不想使用Moment并想显示月份名称-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.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;
      }
    };
  }

我想出了一个局部的解决方案。它使用正则表达式提取月份和日期名称。但是当我浏览区域和语言选项(Windows)时,我意识到不同的文化有不同的格式顺序…也许更好的正则表达式模式会有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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(",") +"

"
+ months.join(","));
    }


1
2
3
4
function getMonthName(month)
{
return ["January","February","March","April","May","June","July","August","September","October","November","December"][parseInt(month)-1]
}


要获取月份名称数组,请执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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/


另一种格式化日期的方法

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

使用这个伴侣

1
2
3
4
function month(a){
var mNames = ["January","February","March","April","May","June","July","August","September","October","November","December" ];
return mNames[a-1];
}


只需在toLocaleString周围写一个简单的包装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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));


我使用的一个快速黑客,它很好地工作:

1
2
3
4
5
6
7
8
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);


只是扩展了许多其他优秀的答案-如果您使用jquery-您可以做一些类似的事情

1
2
3
4
5
6
7
8
9
10
11
12
$.fn.getMonthName = function(date) {

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

    return monthNames[date.getMonth()];

};

其中,date等于var d = new Date(somevalue)。它的主要优点是Per@nickf提到了避免使用全局命名空间。