【问题标题】:.Net webApi ISO datetime and IE8.Net webApi ISO 日期时间和 IE8
【发布时间】:2012-08-31 13:35:07
【问题描述】:

.Net WebAPI 在序列化 DateTime 时默认使用 ISO DateTime 格式。 当 IE8 尝试在 new Date() 构造函数中使用此 ISO DateTime 格式时,它会中断返回 NaN。

var d = new Date('2012-09-06T15:28:56.215Z');
alert(d);

 

Firefox 处理得很好。没试过Chrome。 IE8 中断,返回 NaN。

我假设 ISO 日期是在我的 WebAPI 中使用的一种很好的格式。 我还希望我的 Javascript 客户端能够处理转换为本地时间并重新格式化 DateTime 以便它易于阅读——这就是我使用 Date 类型而不只是将 ISO 日期保留为字符串的原因。

考虑到这一切,对我来说,处理 ISO DateTime 格式以使 IE8 不会阻塞的最佳方法是什么?

【问题讨论】:

    标签: javascript .net datetime browser asp.net-web-api


    【解决方案1】:

    这不是一个完美的解决方案,但如果删除了尾随的“Z”,this Javascript Date library 能够解析该日期。扩展其中一种内置模式来处理时区方面并不难。

    【讨论】:

      【解决方案2】:

      我认为 Date() 构造函数在输入字符串时太不可靠了。

      @Garrett 在这里描述了这个问题 --

      设置日期的可靠方法是构造一个并使用 setFullYear 和 setTime 方法。

      他在这里提供了链接、功能和更多详细信息:https://stackoverflow.com/a/2182529/644492

      我修改了函数以获取完整的 ISO DateTime UTC 字符串输入并返回一个 UTC Date 对象,以后我可以使用 Date getter 来操作该对象。

      我删除了毫秒,因为 IE8 Date 构造函数没有添加毫秒。

      我的修改可能并不完美——正则表达式最后有点松散,可能需要为我的新输入格式更改格式检查块...

      /**Parses string formatted as YYYY-MM-DDThh:mm:ss.sZ 
       * or YYYY-MM-DDThh:mm:ssZ (for IE8), 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-DDThh:mm:ss.sZ, 
       * or YYYY-MM-DDThh:mm:ssZ - Zulu (UTC) Time Only,
       * 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)T(\d\d):(\d\d):(\d\d).*Z\s*$/,
              date = new Date(NaN), month,
              parts = isoExp.exec(dateStringInRange);
          if (parts) {
              month = +parts[2];
              date.setUTCFullYear(parts[1], month - 1, parts[3]);
              date.setUTCHours(parts[4]);
              date.setUTCMinutes(parts[5]);
              date.setUTCSeconds(parts[6]);
              if(month != date.getUTCMonth() + 1) {
                  date.setTime(NaN);
              }
          }
          return date;
      }
      

      【讨论】:

      • 一个更正:if(month != date.getMonth() + 1) 应该是if(month != date.getUTCMonth() + 1)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多