[英]MomentJs Format One Day Behind
我看到了一个与我类似的问题( Moment.js 将日期设置为 1 天后),但我似乎无法应用它。
本质上,我的日期被解析如下:
var date = moment("2019-05-27T00:00:00Z"); // date is the 27th
当我将其格式化以获取日期时,预计 27 日,我反而收到了 26 日!
date.format("DD")
有谁知道为什么会发生这种情况以及如何纠正它?
问题是解析日期的格式。 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
您必须使用moment.utc() , 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.