Gags Gags - 7 months ago 153
Javascript Question

JavaScript new Date() Returning NaN in IE, Safari

I am using highcharts to draw charts and parsing the date with

new Date()
function. In Chrome and FF, date is parsing fine.

But in IE and Safari, i am getting NaN and Invalid date format resp.

Below is the data i am getting from backend in (element.x) array

2016, 04,05
2016, 04,06
2016, 04,07
2016, 04,08
2016, 04,09
2016, 04,10


Now, i am converting it to Date object in JavaScript as below:

//Loop starts
var xAxis = new Date(element.x);
datas.push([Date.UTC(xAxis.getUTCFullYear(),xAxis.getUTCMonth(), xAxis.getUTCDate())]);
//Loop ends


Now, this operation returns NaN in IE but works very well in chrome as below:

Chrome

Array([0]=>140004454) - Unix Time stamp i get


IE

Array([0]=>NaN)

Answer

The way new Date(dateString) parses dateString varies for different browsers, with some browsers being more flexible than others.

The safest way to create your date, is to split up your element.x into its components, convert those components to integer values and create a new date using the syntax new Date(year, month, day).

So, instead of ...

var xAxis = new Date(element.x);

... create your date like this :

var xvals = element.x.split(',');
var xAxis = new Date(
    parseInt(xvals[0].trim()),
    parseInt(xvals[1].trim()) - 1,
    parseInt(xvals[2].trim())
);

That should work in all browsers!