Javascript Date(dateString) returns NaN on specifi

2020-03-16 03:25发布

问题:

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?

回答1:

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?

/**Parses string formatted as YYYY-MM-DD to a Date object.
   * If the supplied string does not match the format, an 
   * invalid Date (value NaN) is returned.
   * @param {string} dateStringInRange format YYYY-MM-DD, with year in
   * range of 0000-9999, inclusive.
   * @return {Date} Date object representing the string.
   */
  function parseISO8601(dateStringInRange) {
    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);

    if(parts) {
      month = +parts[2];
      date.setFullYear(parts[1], month - 1, parts[3]);
      if(month != date.getMonth() + 1) {
        date.setTime(NaN);
      }
    }
    return date;
  }

Source: http://jibbering.com/faq/#parseDate



回答2:

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



回答3:

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.



回答4:

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