Yansen Tan Yansen Tan - 1 year ago 159
Javascript Question

Moment.js: Convert from date string

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

I tried using this, but it returns NaN:

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

Answer Source

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:

moment('Apr 2016', 'MMM YYYY').get('month') + 1 // = 4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download