.Net webApi ISO日期时间和IE8

.Net webApi ISO datetime and IE8

本文关键字:IE8 时间 日期 webApi ISO Net      更新时间:2023-09-26

。NetWebAPI在序列化DateTime时默认使用ISO DateTime格式。当IE8试图在新的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就不会窒息?

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

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

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

他在这里给出了一个链接、一个函数和更多细节:https://stackoverflow.com/a/2182529/644492

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

我删除了毫秒,因为IE8Date构造函数不添加毫秒。

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

/**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;
}

这不是一个完美的解决方案,但如果去掉尾部的"Z",这个Javascript日期库能够解析该日期。扩展其中一个内置模式来处理时区方面并不困难。