var d = new Date();
That’s fine if we want get the current date and time, however it doesn’t help us much if we are planning on working with a date in the past or future. In this instance we would need to pass a date as a parameter to the code above.
The problem I wanted to discuss today is specific to Internet Explorer and Safari and is about how passing a date as shown below doesn’t work as expected:
var d = new Date("2011-02-07"); alert(d);
var d = new Date("2011-02-07T11:05:00"); alert(d);
If you were run the above code snippets across various browsers you would see that in IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’. Firefox, Chrome and Opera however will output the correct date.
The problem lies in the format that you pass the required date to the Date() object. For some reason, and don’t ask me why, the two aforementioned browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail. I haven’t managed to compile a definitive list of supported date formats, however I can tell you the following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss var d = new Date("02/07/2011"); // "mm/dd/yyyy" var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss" var d = new Date(1297076700000); // milliseconds var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC