JavaScript new Date Returning NaN in IE

JavaScript new Date() Returning NaN in IE

Hello Readers,

When it comes to programming, working with dates can be a bit tricky. Fortunately, most languages have done the hard work already and come with some kind of built-in date functionality to assist us.

JavaScript in particular has lots of useful functions to aid in getting, setting and outputting dates.

JavaScript new Date() Returning NaN in IE #javascript #date #error #NaN Click To Tweet

The JavaScript Date Object

To start working with dates in JavaScript, the first thing you need to do is initialize a date object as shown below:

The above piece of code is fine if we want to get the current date and time. However, it doesn’t help much if we need to work getting or setting the past or future date. In this case, we would need to pass a date as a parameter to the code above.

NaN Error – The Problem

The problem mentioned here is specific to Internet Explorer and Safari. When we pass a date as shown below it doesn’t works as expected:

OR

If you run the above code snippets on various browsers, you would see that in IE you get “NaN” and in Safari you get “Invalid Date“. Firefox, Chrome and Opera will output the date correctly as expected.

JavaScript new Date Returning NaN in IE

JavaScript NaN Error in IE but not in Firefox, Chrome

NaN Error – The Solution

The problem lies in the format of the date which is being passed to the Date() object.

For some reason, the two browsers – internet explorer and safari do not support the date format “yyyy-mm-dd” and therefore fail.

The following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:


That’s all folks regarding the error JavaScript new Date() returning NaN in IE. Hope you were able to follow the post and got the understanding about the error. If you want to read some of my posts related to JavaScript then here is the link – Few more posts on JavaScript and jQuery.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Scripting!