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

前端 未结 4 532
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 04:41

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

4条回答
  •  情话喂你
    2021-01-12 05:16

    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

提交回复
热议问题