不同浏览器中日期值的JSON.stringify差异 [英] Discrepancy in JSON.stringify of date values in different browsers

查看:65
本文介绍了不同浏览器中日期值的JSON.stringify差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML页面中有这个代码:

I have this code in an HTML page:

alert(JSON.stringify(new Date()));

我包括最新的 json2.js (2009-09-29版本)在我的页面中支持没有JSON.stringify()的旧浏览器。我还包括jquery-1.3.2.js。我相信具有原生JSON支持的新浏览器,它只是传递给原生JSON功能。

I'm including the latest json2.js (2009-09-29 version) in my page to support older browsers without JSON.stringify(). I also have jquery-1.3.2.js included. I believe in newer browsers with native JSON support, it just passes through to the native JSON feature.

这是我在不同浏览器中得到的结果:

Here's the results I get in different browsers:

IE 8 on Windows XP: "2010-02-07T21:39:32Z"
Chrome 4.0 on Windows XP: "2010-02-07T21:39:59Z"
Firefox 3.0 of Windows XP: "2010-02-07T21:40:41Z"
Chrome 4.0 on Ubuntu linux:  "2010-02-07T21:41:49Z"
Firefox 3.0 on Ubuntu linux:  "2010-02-07T21:42:44Z"
Chrome 4.0 on Mac OSX: "2010-02-07T21:43:56Z"
Safari on Mac OSX: "2010-02-07T21:45:21Z"
Firefox 3.5 on Mac OSX: "2010-02-07T21:44:10.101Z"

注意最后一个?它包含毫秒,而其他任何一个都没有。我没有在任何其他系统上安装FF3.5,但我假设它们会有相同的结果。

Notice the last one? It contains milliseconds, and none of the others do. I don't have FF3.5 installed on any other systems, but I'm assuming they would have the same results.

我能做些什么来做所有所有平台上的日期字符串相同吗?我的后端REST服务可以配置一个格式字符串来反序列化JSON日期,但它不能支持多种格式,只有一种格式。

Is there something I can do to make all dates on all platforms stringify the same? My backend REST service can be configured with a format string to deserialize JSON dates, but it can't support multiple formats, just one.

推荐答案

我有这个工作添加以下javascript:

I got this working adding the following javascript:

// Added to make dates format to ISO8601
Date.prototype.toJSON = function (key) {
    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    return this.getUTCFullYear()   + '-' +
         f(this.getUTCMonth() + 1) + '-' +
         f(this.getUTCDate())      + 'T' +
         f(this.getUTCHours())     + ':' +
         f(this.getUTCMinutes())   + ':' +
         f(this.getUTCSeconds())   + '.' +
         f(this.getUTCMilliseconds())   + 'Z';
};

我确信这可能会减慢序列化速度,但它似乎可以使浏览器保持一致。

I'm sure this probably slows down the serialization, but it seems to make things consistent across browsers.

这篇关于不同浏览器中日期值的JSON.stringify差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆