I'm using the Javascript Date(string) constructor with a date format of "yyyy-mm-dd". The constructor works just fine in IE 9 and Firefox unless the app is running on our testing VM which is running IIS. If it's on the VM, in IE 9 it returns 'NaN', but still works normally in Firefox.
var dateAsString = "2011-11-09";
var dateCreated = new Date(dateAsString);
I was under the assumption that the server had nothing to do with client-side Javascript. Any suggestions?
Just use slashes instead of hyphens if you can.
EDIT: Expanded clarification...
The ISO 8601 standard format uses the hyphen as a date separator. My answer does not mean you do not need to follow standards. You can use slashes only for the Date constructor if necessary.
I suggest attempting a more reliable form of date parsing. The example below uses
setFullYear()
. Does IE produce a different result with the code below?Source: http://jibbering.com/faq/#parseDate
And for those of us who want to know how to replace hyphens (aka dashes) with slashes:
That uses this function:
In my case it's much easier to convert hyphens to slashes selectively (only where it's needed for the Date() function) than to replace the date format everywhere in my code.
Note: you really need to define a separate 'response' variable and assign it the value of the replace operation result. If you don't, the string is returned unaltered in Chrome. That's not a huge problem, since Chrome doesn't have a problem with hyphenated date strings to begin with. But still...
It's because of the date format. For some reason, IE and Safari get tripped up with
yyyy-mm-dd
. Use another date format and you should be all set.It's talked about here:
http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari