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

Jam*_*sen 241 javascript datetime iso8601

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

<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
Run Code Online (Sandbox Code Playgroud)

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

我尝试过以下方法:

function isoDate(msSinceEpoch) {

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

}
Run Code Online (Sandbox Code Playgroud)

但这给了我:

"2010-4-2T3:19"
Run Code Online (Sandbox Code Playgroud)

Ana*_*nov 441

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

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

如果,不知何故,你在浏览器上不支持它,我已经覆盖了你:

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';
    };

  }() );
}
Run Code Online (Sandbox Code Playgroud)

  • @JosephLennox 那是哥谭市的时间吗? (5认同)
  • .toISOString() 肯定会返回 UTC 中的日期? (4认同)
  • 不是在所有浏览器中,如上所述:http://kangax.github.com/es5-compat-table/ (3认同)
  • 在OP提供的示例中,没有毫秒或时区。 (2认同)

dev*_*ler 63

请参阅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
Run Code Online (Sandbox Code Playgroud)

  • OP 提供的示例 (`&lt;abbr title="2010-04-02T14:12:07"&gt;`) 没有时区。也许他们想要当地时间,这对 UI 时间字符串有意义吗? (2认同)

Dan*_*l F 60

Web上几乎每个to-ISO方法都会在输出字符串之前通过应用转换为"Z"ulu时间(UTC)来丢弃时区信息.浏览器的原生.toISOString()也会删除时区信息.

这会丢弃有价值的信息,因为服务器或收件人始终可以将完整的ISO日期转换为Zulu时间或其所需的时区,同时仍然可以获取发件人的时区信息.

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

使用时区信息和毫秒获取当前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() 
Run Code Online (Sandbox Code Playgroud)

获取具有时区信息但没有毫秒的本机JavaScript Date对象的ISO时间

var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
Run Code Online (Sandbox Code Playgroud)

这可以与Date.js结合使用以获取Date.today()等函数,然后将其结果传递给片刻.

像这样格式化的日期字符串是JSON编译器,并且非常适合存储到数据库中.Python和C#似乎喜欢它.

  • 不要约会与约会的人.只需使用moment.js并保存你的头发. (19认同)
  • 你实际上可以省略这样的格式:`moment(new Date()).format()`."从版本1.5.0开始,调用没有格式的时刻#格式将默认为...... ISO8601格式`YYYY-MM-DDTHH:mm:ssZ`".Doc:从http://momentjs.com/docs/#/displaying/fromnow/向上滚动 (3认同)

arc*_*don 26

提出的问题是ISO格式,精度降低.瞧:

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

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


you*_*es0 13

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

new Date().toJSON()
Run Code Online (Sandbox Code Playgroud)


Rus*_*vis 12

如果您不需要支持IE7,以下是一个非常简洁的黑客:

JSON.parse(JSON.stringify(new Date()))
Run Code Online (Sandbox Code Playgroud)

  • 用什么方法比.toISOString()更好? (2认同)

Cha*_*rns 6

我通常不想显示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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)


Use*_*gle 5

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

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

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

243041 次

最近记录:

7 年,1 月 前