如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
这是一种不依赖于硬编码数组并支持多个区域设置的方法。
如果你需要一个完整的数组:
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;
};
用法:
console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]
如果你只需要一个选定的月份(更快):
var monthLocalizedString = function(month, locale) {
return new Date(2010,month).toLocaleString(locale,{month:"long"});
};
用法:
console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> февруари
console.log(monthLocalizedString(1, 'de')); // -> Februar
经过测试,在Chrome和IE 11上运行良好。在mozilla上需要做一些修改,因为它返回整个日期。
其他回答
我是通过DatePipe完成的。
const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');
你可以像这样在构造函数中注入默认区域:
constructor(@Inject(LOCALE_ID) private locale: string){}
Angular的引用https://angular.io/api/common/DatePipe
不幸的是,提取月份名称的最佳方法是从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'
对我来说,这是最佳解,
对于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"]
将名称存储在一个数组中,并根据月份的索引进行查找。
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()方法
最简单最简单的方法:
const dateStr =新的日期(2020,03,10).toDateString();//“2020年4月10日星期五” const dateStrArr = dateStr。分割(' ');// ['Fri', 'Apr', '10', '2020'] console.log (dateStrArr [1]);/ / 4月的
将日期转换为字符串。 间隔一个空格。 从数组中选择第二个元素。