将正常日期转换为ISO-8601格式 [英] Converting a normal date to ISO-8601 format

查看:454
本文介绍了将正常日期转换为ISO-8601格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在Javascript中输出ISO-8601格式的字符串?

我有个约会日期

Thu Jul 12 2012 01:20:46 GMT+0530

如何将其转换为ISO-8601格式

How can I convert it into ISO-8601 format like this

2012-07-12T01:20:46Z


推荐答案

在大多数较新的浏览器中,你有 .toISOString()方法,但在IE8或更老版本中你可以使用以下内容(取自Douglas Crockford的 json2.js ):

In most newer browsers you have .toISOString() method, but in IE8 or older you can use the following (taken from json2.js by Douglas Crockford):

// Override only if native toISOString is not defined
if (!Date.prototype.toISOString) {
    // Here we rely on JSON serialization for dates because it matches 
    // the ISO standard. However, we check if JSON serializer is present 
    // on a page and define our own .toJSON method only if necessary
    if (!Date.prototype.toJSON) {
        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())   + 'Z';
        };
    }

    Date.prototype.toISOString = Date.prototype.toJSON;
}

现在你可以安全地调用`.toISOString()方法。

Now you can safely call `.toISOString() method.

这篇关于将正常日期转换为ISO-8601格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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