如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
对于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()方法
如果你使用剑道,也可以这样做。
kendo.toString(dateobject, "MMMM");
以下是kendo网站上的格式化器列表:
"d" Renders the day of the month, from 1 through 31. "dd" The day of the month, from 01 through 31. "ddd" The abbreviated name of the day of the week. "dddd" The full name of the day of the week. "f" The tenths of a second in a date and time value. "ff" The hundredths of a second in a date and time value. "fff" The milliseconds in a date and time value. "M" The month, from 1 through 12. "MM" The month, from 01 through 12. "MMM" The abbreviated name of the month. "MMMM" The full name of the month. "h" The hour, using a 12-hour clock from 1 to 12. "hh" The hour, using a 12-hour clock from 01 to 12. "H" The hour, using a 24-hour clock from 1 to 23. "HH" The hour, using a 24-hour clock from 01 to 23. "m" The minute, from 0 through 59. "mm" The minute, from 00 through 59. "s" The second, from 0 through 59. "ss" The second, from 00 through 59. "tt" The AM/PM designator. "yy" The last two characters from the year value. "yyyy" The year full value. "zzz" The local timezone when using formats to parse UTC date strings.
如果你赶时间……那就给你!
const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
预期产出:“四月”
较短的版本:
const monthNames = ["January", "February", "March", "April", "May", "June", “七月”,“八月”,“九月”,“十月”,“十一月”,“十二月” ]; const d = new Date(); 文档。write("当前月份是" + monthNames[d.getMonth()]);
注(2019-03-08)-我最初在2009年写的这个答案已经过时了。请参阅David Storey的回答以获得更好的解决方案。
我们不需要声明一个包含所有月份名称的数组,然后用一个索引来指向,我们也可以把它写成一个简短的版本,如下所示:
var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug