如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
对我来说,这是最佳解,
对于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"]
其他回答
您可以使用几种可用的日期格式化程序之一。因为这属于JavaScript规范,所以它可以在浏览器和服务器端模式下使用。
objDate.toString().split(" ")[1]; // gives short name, unsure about locale
objDate.toLocaleDateString.split(" ")[0]; // gives long name
e.g.
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
如果您不想使用时刻,并希望显示月份名称-
.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;
}
};
}
文档。写(新日期()。toLocaleString('en-us',{月:'长',年:'数字',日:'数字'}))
我是通过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
我用了一个很有效的小窍门:
const monthNumber = 8; const yearNumber = 2018; const date = ' ${['Jan', 'Feb', 'Mar', 'Apr', “五月”,“六月”,“七月”,“八月”, 'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1] } $ {yearNumber} '; console.log(日期);