如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
我们不需要声明一个包含所有月份名称的数组,然后用一个索引来指向,我们也可以把它写成一个简短的版本,如下所示:
var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
其他回答
对我来说,这是最佳解,
对于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"]
最简单最简单的方法:
const dateStr =新的日期(2020,03,10).toDateString();//“2020年4月10日星期五” const dateStrArr = dateStr。分割(' ');// ['Fri', 'Apr', '10', '2020'] console.log (dateStrArr [1]);/ / 4月的
将日期转换为字符串。 间隔一个空格。 从数组中选择第二个元素。
文档。写(新日期()。toLocaleString('en-us',{月:'长',年:'数字',日:'数字'}))
date对象中一些常见的简单处理可以通过它来完成。
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()))
或者你可以制作日期原型
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())
Ex:
var dateentt3新日期()#发情
var dateFormat4 = new Date().getFormatDate();# 16 三月, 2017
如果您不介意扩展Date原型(并且有一些很好的理由不想这样做),您实际上可以提出一个非常简单的方法:
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 Date对象。