Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date(dateString) returns NaN on specific server and browser

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?

like image 376
Gagege Avatar asked Nov 11 '11 19:11

Gagege


Video Answer


2 Answers

And for those of us who want to know how to replace hyphens (aka dashes) with slashes:

new Date(dashToSlash(string));

That uses this function:

function dashToSlash(string){
  var response = string.replace(/-/g,"/");
  //The slash-g bit says: do this more than once
  return response;
}

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...

like image 113
Wytze Avatar answered Oct 07 '22 13:10

Wytze


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.

like image 44
Lee Kowalkowski Avatar answered Oct 07 '22 14:10

Lee Kowalkowski