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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:58:17  来源:igfitidea点击:

How do I output an ISO 8601 formatted string in JavaScript?

javascriptdatetimeiso8601

提问by James A. Rosen

I have a Dateobject. How do I render the titleportion of the following snippet?

我有一个Date对象。如何呈现title以下代码段的部分?

<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>

I have the "relative time in words" portion from another library.

我有另一个图书馆的“相对时间”部分。

I've tried the following:

我尝试了以下方法:

function isoDate(msSinceEpoch) {

   var d = new Date(msSinceEpoch);
   return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
          d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();

}

But that gives me:

但这给了我:

"2010-4-2T3:19"

回答by Anatoly Mironov

There is already a function called toISOString():

已经有一个名为 的函数toISOString()

var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"

If, somehow, you're on a browserthat doesn't support it, I've got you covered:

如果不知何故,您使用的浏览器不支持它,我会为您提供帮助:

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      var r = String(number);
      if ( r.length === 1 ) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear()
        + '-' + pad( this.getUTCMonth() + 1 )
        + '-' + pad( this.getUTCDate() )
        + 'T' + pad( this.getUTCHours() )
        + ':' + pad( this.getUTCMinutes() )
        + ':' + pad( this.getUTCSeconds() )
        + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
        + 'Z';
    };

  }() );
}

回答by dev-null-dweller

See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:

请参阅页面https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date上的最后一个示例:

/* Use a function for the exact format desired... */
function ISODateString(d) {
    function pad(n) {return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
         + pad(d.getUTCMonth()+1)+'-'
         + pad(d.getUTCDate())+'T'
         + pad(d.getUTCHours())+':'
         + pad(d.getUTCMinutes())+':'
         + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z

回答by Daniel F

Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.

几乎所有网络上的 to-ISO 方法都通过在输出字符串之前应用转换为“Z”ulu 时间 (UTC) 来删除时区信息。浏览器的原生 .toISOString() 也会删除时区信息。

This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.

这会丢弃有价值的信息,因为服务器或收件人始终可以将完整的 ISO 日期转换为祖鲁语时间或它需要的任何时区,同时仍能获取发件人的时区信息。

The best solution I've come across is to use the Moment.jsjavascript library and use the following code:

我遇到的最佳解决方案是使用Moment.jsjavascript 库并使用以下代码:

To get the current ISO time with timezone information and milliseconds

使用时区信息和毫秒获取当前 ISO 时间

now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"

now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"

now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString() 

To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds

获取包含时区信息但不包含毫秒的原生 JavaScript Date 对象的 ISO 时间

var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")

This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.

这可以与 Date.js 结合使用以获得类似 Date.today() 的函数,然后可以将其结果传递给 moment。

A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.

像这样格式化的日期字符串是 JSON 兼容的,并且很适合存储到数据库中。Python 和 C# 似乎喜欢它。

回答by arcseldon

The question asked was ISO format withreduced precision. Voila:

问的问题是ISO格式降低精度。瞧:

 new Date().toISOString().slice(0, 19) + 'Z'
 // '2014-10-23T13:18:06Z'

Assuming the trailing Z is wanted, otherwise just omit.

假设需要尾随 Z,否则只需省略。

回答by younes0

Shortest, but not supported by Internet Explorer 8 and earlier:

最短,但不受 Internet Explorer 8 及更早版本支持:

new Date().toJSON()

回答by Russell Davis

If you don't need to support IE7, the following is a great, concise hack:

如果你不需要支持 IE7,下面是一个很棒的、简洁的 hack:

JSON.parse(JSON.stringify(new Date()))

回答by Charles Burns

I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a localISO date, I use the function:

我通常不想显示 UTC 日期,因为客户不喜欢在他们的脑海中进行转换。要显示本地ISO 日期,我使用以下函数:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;
};

The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

上面的函数省略了时区偏移信息(除非本地时间恰好是 UTC),所以我使用下面的函数来显示单个位置的本地偏移。如果您希望每次都显示偏移量,您还可以将其输出附加到上述函数的结果中:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))
};

toLocalIsoStringuses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

toLocalIsoString使用pad. 如果需要,它几乎可以像任何 pad 功能一样工作,但为了完整起见,这是我使用的:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    }
    return str;
}

回答by kaiz.net

There is a '+' missing after the 'T'

“T”后面缺少一个“+”

isoDate: function(msSinceEpoch) {
  var d = new Date(msSinceEpoch);
  return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
         + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}

should do it.

应该这样做。

For the leading zeros you could use this from here:

对于前导零,您可以从这里使用它:

function PadDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

Using it like this:

像这样使用它:

PadDigits(d.getUTCHours(),2)

回答by Sean

function timeStr(d) { 
  return ''+
    d.getFullYear()+
    ('0'+(d.getMonth()+1)).slice(-2)+
    ('0'+d.getDate()).slice(-2)+
    ('0'+d.getHours()).slice(-2)+
    ('0'+d.getMinutes()).slice(-2)+
    ('0'+d.getSeconds()).slice(-2);
}

回答by Useful Angle

The problem with toISOString is that it gives datetime only as "Z".

toISOString 的问题在于它仅将日期时间指定为“Z”。

ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).

ISO-8601 还以小时和分钟为单位定义了具有时区差异的日期时间,格式为 2016-07-16T19:20:30+5:30(当时区提前 UTC)和 2016-07-16T19:20:30-01 :00(当时区落后于 UTC 时)。

I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.

对于这么小的任务,我认为使用另一个插件 moment.js 不是一个好主意,尤其是当您可以通过几行代码获得它时。



    var timezone_offset_min = new Date().getTimezoneOffset(),
        offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
        offset_min = Math.abs(timezone_offset_min%60),
        timezone_standard;

    if(offset_hrs < 10)
        offset_hrs = '0' + offset_hrs;

    if(offset_min > 10)
        offset_min = '0' + offset_min;

    // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
    // So add an opposite sign to the offset
    // If offset is 0, it means timezone is UTC
    if(timezone_offset_min < 0)
        timezone_standard = '+' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min > 0)
        timezone_standard = '-' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min == 0)
        timezone_standard = 'Z';

    // Timezone difference in hours and minutes
    // String such as +5:30 or -6:00 or Z
    console.log(timezone_standard); 


Once you have the timezone offset in hours and minutes, you can append to a datetime string.

获得以小时和分钟为单位的时区偏移量后,您可以附加到日期时间字符串。

I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

我写了一篇关于它的博客文章:http: //usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes