MomentJs Format One Day Behind

纵然是瞬间 提交于 2021-02-19 08:45:17

问题


I have seen a question that is similar to mine (Moment.js sets dates to 1 day behind) but I can't seem to apply it.

Essentially, my date gets parsed like this:

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

When I format it to get the day, expecting the 27th, I instead receive the 26th!

date.format("DD")

Does anyone know why this might be happening and how to correct it?

http://jsfiddle.net/rmdxj26e/


回答1:


You must use moment.utc(), the Moment documentation says:

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 Output:

Live example:

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>



回答2:


The problem is the format of the parsed date. The Z letter means it is a "Zulu time" (UTC). I don't know what is your timezone, but the date is converted to your timezone.

You can parse local time format (without Z) and it should display properly.

So the full code with explanation:

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


来源:https://stackoverflow.com/questions/56080029/momentjs-format-one-day-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!