【问题标题】:MomentJs Format One Day BehindMomentJs 格式落后一天
【发布时间】:2019-05-10 14:50:03
【问题描述】:

我看到了一个与我的 (Moment.js sets dates to 1 day behind) 类似的问题,但我似乎无法应用它。

基本上,我的日期是这样解析的:

var date = moment("2019-05-27T00:00:00Z"); // date is the 27th

当我将其格式化为当天,期待 27 日,我却收到了 26 日!

date.format("DD")

有谁知道为什么会发生这种情况以及如何纠正它?

http://jsfiddle.net/rmdxj26e/

【问题讨论】:

  • @RokoC.Buljan 因为你的时区不同 :)
  • 请尝试删除“Z”。

标签: javascript date momentjs


【解决方案1】:

您必须使用moment.utc()Moment documentation 表示:

默认情况下,moment 解析并显示为当地时间。

如果你想以 UTC 解析或显示时刻,你可以使用 moment.utc() 而不是 moment()。

这为我们带来了 Moment.js 的一个有趣特性。 UTC 模式。

在 UTC 模式下,所有显示方式均以 UTC 时间显示 而不是当地时间。

moment().format();     // 2013-02-04T10:35:24-08:00  
moment.utc().format(); // 2013-02-04T18:35:24+00:00

jsFiddle 输出

实例:

var date = moment.utc("2019-05-27T00:00:00Z");
$('#date').append($('<p>').html(date.format("DD")));
$('#date').append($('<p>').html(date.local().format("DD")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="date"></div>

【讨论】:

  • 感谢 Fraction - 这就是我想要的。我不喜欢随意切掉“Z”。
【解决方案2】:

问题在于解析日期的格式。 Z 字母表示它是“祖鲁时间”(UTC)。我不知道您的时区是什么,但日期已转换为您的时区。

您可以解析本地时间格式(不带Z),它应该可以正常显示。

所以完整的代码和解释:

var date = moment("2019-05-27T00:00:00"); // date is the 27th in local time
$('#date').append($('<p>').html(date.utc().format("DD"))); // can display 26th or 27th depends on local timezone on the PC
$('#date').append($('<p>').html(date.local().format("DD"))); // is still local so it will be 27th

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多