Doan Minh Tien Doan Minh Tien - 1 year ago 115
Javascript Question

Convert ISO Date string to date in Javascipt

Need help to convert exactly from ISO Date string to Date:
I have an ISO string date: "2016-01-23T22:23:32.927".
But when I use

new Date(dateString)
to convert Date, the result is wrong:

var date = new Date("2016-01-23T22:23:32.927");

The result is:
Sun Jan 24 2016 05:23:32 GMT+0700
. It's not true. I want the date is 23 not 24.

Please help me. Thanks a lot!

Answer Source

If you're willing and able to add a dependency, I recommend using moment.js for this. It makes date handling in Javascript much more straightforward and a lot safer, and fixes your specific problem right out of the box.

To do this, 1st load it from a CDN, e.g. Moment.JS 2.14.1 minified. Then use it as follows:

var date = moment("2016-01-23T22:23:32.927");
// output:  Sat Jan 23 2016 22:23:32 GMT-0500

...i.e. your desired result :)

Here's a jsfiddle demonstrating this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download