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.
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:
var date = new Date("2016-08-26");
var date = new Date("2016-08-26T10:05:00");
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.
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:
var date = new Date(2016, 08, 26); // yyyy, mm-1, dd
var date = new Date(2016, 08, 26, 10, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var date = new Date("26/08/2016"); // "mm/dd/yyyy"
var date = new Date("08/26/2016 10:05:00"); // "mm/dd/yyyy hh:mm:ss"
var date = new Date("Mon Feb 26 2016 10:05:00 GMT"); // "Day Mon dd yyyy"
What do you think?
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.