如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
只是扩展了许多其他优秀的答案-如果你正在使用jQuery -你可以做一些类似的事情
$.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)。这样做的主要优点是@nickf避免使用全局名称空间。
其他回答
对于momentjs,只需使用格式符号。
const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August
Try:
var objDate = new Date("10/11/2009");
var strDate =
objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
objDate.toLocaleString("en", { month: "long" }) + ' ' +
objDate.toLocaleString("en", { year: "numeric"});
对我来说,这是最佳解,
对于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"]
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();
我用了一个很有效的小窍门:
const monthNumber = 8; const yearNumber = 2018; const date = ' ${['Jan', 'Feb', 'Mar', 'Apr', “五月”,“六月”,“七月”,“八月”, 'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1] } $ {yearNumber} '; console.log(日期);