Moment.js:从日期字符串转换

时间:2022-08-25 10:52:29

How do I get month and year from date like "Apr 2015" or "Dec 2016" with moment.js?

如何通过moment.js获取“2015年4月”或“2016年12月”之类的月份和年份?

I tried using this, but it returns NaN:

我尝试使用它,但它返回NaN:

var date = 'Apr 2016';
console.log(moment(date).get('month')); // I want it to return 4

1 个解决方案

#1


0  

You have to specify the date format explicitly when parsing a non ISO 8601 string or a string not recognized by new Date(string). Increment the result by one, as the range is 0 … 11:

解析非ISO 8601字符串或新日期(字符串)无法识别的字符串时,必须明确指定日期格式。将结果增加1,范围为0 ... 11:

moment('Apr 2016', 'MMM YYYY').get('month') + 1 // = 4

#1


0  

You have to specify the date format explicitly when parsing a non ISO 8601 string or a string not recognized by new Date(string). Increment the result by one, as the range is 0 … 11:

解析非ISO 8601字符串或新日期(字符串)无法识别的字符串时,必须明确指定日期格式。将结果增加1,范围为0 ... 11:

moment('Apr 2016', 'MMM YYYY').get('month') + 1 // = 4