Michael Michael - 1 year ago 56
Javascript Question

What the elegant way to convert date in string to Date object?

I have this date in string format:

"05/2016" or "12/2015"

How can I convert the dates above in string format to Date() javascript object?

Answer Source

Date constructor accepts params in next order: year, month, day, hours, minutes, seconds, milliseconds, so simply parse string and pass it into Date constructor.

var data = "05/2016".split('/');
// Add + before year to convert str into number. Decrease second param because month starts from 0..11. 
var date = new Date(+data[1],data[0]  - 1);

Also, you can convert your string to format which would be parsed correctly by new Date ( See more about dateString in MDN Date.parse description.

// convert string "05/2016" -> "2016-05"
var dateString = "05/2016".split('/').reverse().join('-');
var date = new Date(dateString);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download