【问题标题】:moment date parsing in JSJS中的时刻日期解析
【发布时间】:2016-07-12 20:03:00
【问题描述】:

使用矩js

var y = moment('2016-01-11T16:00:00');
   console.log('UTC ' + moment().utc().format());
   console.log('Local ' + moment().format());
   console.log(y.format());
   console.log(y.toISOString());

以上代码输出

UTC 2016-07-12T19:54:15Z
Local 2016-07-12T15:54:15-04:00
2016-01-11T16:00:00-05:00
2016-01-11T21:00:00.000Z

为什么它在 y.format() 中显示 -05:00 偏移量。

【问题讨论】:

标签: javascript date momentjs


【解决方案1】:

.format() 旨在采用一个参数,该参数使您可以准确地格式化日期以如何显示它。由于您不传递参数,因此它为您提供默认值,在这种情况下,显示时区 (-05:00)。根据docs

从 1.5.0 版开始,在没有格式的情况下调用 moment#format 将 默认为 moment.defaultFormat。开箱即用,moment.defaultFormat 是ISO8601格式YYYY-MM-DDTHH:mm:ssZ

从 2.13.0 版本开始,在 UTC 模式下,将返回默认格式 Z 作为偏移量,而不是 +00:00。

查看链接以获取有关使用.format() 格式化日期的信息。

【讨论】:

  • 我应该更清楚。当 moment().format() 打印 2016-07-12T15:54:15-04:00 时,我理解它默认为 ISO8601 但 moment('2016-01-11T16:00:00').format() 打印 2016 -01-11T16:00:00-05:00 为什么是 -5 而不是 -4(这是 EST -4 是正确的偏移量)。这是否意味着无论本地时区如何,它总是默认为 -5 偏移量?还是不考虑-5有意义的夏令时
  • 没有注意到它是 1 月 11 日。所以 -5 有意义。
【解决方案2】:

moment 将默认为 ISO 8601(与 UTC 有偏移的当地时间),查看moment docs 的文档,以及ISO 8601 Standard 上有关标准本身的更多信息

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多