如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
文档。写(新日期()。toLocaleString('en-us',{月:'长',年:'数字',日:'数字'}))
其他回答
您可以使用几种可用的日期格式化程序之一。因为这属于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
我用了一个很有效的小窍门:
const monthNumber = 8; const yearNumber = 2018; const date = ' ${['Jan', 'Feb', 'Mar', 'Apr', “五月”,“六月”,“七月”,“八月”, 'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1] } $ {yearNumber} '; console.log(日期);
对于momentjs,只需使用格式符号。
const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August
将名称存储在一个数组中,并根据月份的索引进行查找。
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()方法
不幸的是,提取月份名称的最佳方法是从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'