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?
/
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/rmdxj26e/
Share Improve this question edited May 10, 2019 at 14:55 user1477388 asked May 10, 2019 at 14:50 user1477388user1477388 21.4k33 gold badges151 silver badges275 bronze badges 2- 1 @RokoC.Buljan because your timezone is different :) – Piotr Stapp Commented May 10, 2019 at 14:56
- Please try removing the "Z". – Yannick K Commented May 10, 2019 at 14:57
2 Answers
Reset to default 5The 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
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./ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="date"></div>