如何在 JavaScript 中输出 ISO 8601 格式的字符串? [英] How do I output an ISO 8601 formatted string in JavaScript?

查看:33
本文介绍了如何在 JavaScript 中输出 ISO 8601 格式的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Date object. How do I render the title portion of the following snippet?

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

我有另一个图书馆的相对时间"部分.

我尝试了以下方法:

function isoDate(msSinceEpoch) {

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

}

但这给了我:

"2010-4-2T3:19"

推荐答案

已经有一个函数叫做 toISOString():

There is already a function called toISOString():

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

如果,不知何故,你在 不支持它的浏览器,我已经帮你解决了:

If, somehow, you're on a browser that 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';
    };

  }());
}

console.log(new Date().toISOString())

这篇关于如何在 JavaScript 中输出 ISO 8601 格式的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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