gpt4 book ai didi

javascript - MomentJs格式落后一天

转载 作者:行者123 更新时间:2023-11-30 08:19:32 25 4
gpt4 key购买 nike

我看到一个与我的问题类似的问题 ( 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/

enter image description here

最佳答案

您必须使用 moment.utc() , Moment documentation说:

By default, moment parses and displays in local time.

If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

This brings us to an interesting feature of Moment.js. UTC mode.

While in UTC mode, all display methods will display in UTC time instead of local time.

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

jsFiddle 输出:

enter image description here

实例:

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>

关于javascript - MomentJs格式落后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com