如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
您可以使用datejs来实现这一点。检查格式说明符,MMMM给出了月份的名称:
var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
datejs本地化了超过150个locale !在这里看到的
其他回答
获取月份名称的数组:
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/
如果你使用剑道,也可以这样做。
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.
如果你赶时间……那就给你!
const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
预期产出:“四月”
对我来说,这是最佳解,
对于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;
};
输出是
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
不幸的是,提取月份名称的最佳方法是从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'