I'm having trouble parsing dates for my website. It used to work fine on both IE and Chrome (I haven't tried Firefox yet). But recently I have been unable to parse dates on chrome.
The date string which I obtain from the database looks like this "Oct 17 2016 12:00AM"
Here is the code I'm using to debug my problem
console.log("String = "+item.DueDate);
console.log("new Date = " + new Date(item.DueDate));
console.log("Date Parse = " + Date.parse(item.DueDate));
console.log("Moment Parse = " + moment(item.DueDate));
Here is what is returned by IE:
String = Oct 17 2016 12:00AM
new Date = Mon Oct 17 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date Parse = 1476676800000
Moment Parse = 1476676800000
And here is what is returned by Chrome:
String = Oct 17 2016 12:00AM
new Date = Invalid Date
Date Parse = NaN
Moment Parse = NaN
I use Date.parse() in one of my function that finds the difference between to dates:
function daydiff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
var dif = daydiff(Date.parse(item.DueDate), Date.parse(item.DateShipped));
What should I do to my date string in order for it to work with both chrome and internet explorer?
Fixed
So I fixed it by changing my web api call to return a DateTime rather than string.
Never parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it is almost entirely implementation dependent. Even the one format specified in ECMA-262 is not reliably parsed by all browsers in use.
Use a bespoke function or a library that provides parsing and formatting and always pass the format to parse to the parser. Suitable libraries are moment.js, date.js and fecha.js, but there are many others.
A bespoke function might look like:
Whereas using a library would look like: