Reputation: 293
Moment suddenly started to format dates incorrectly. Like, completely changing them. I don't understand why. I made a short video so you can see what's going on here: https://youtu.be/WPLDiiWsfAo
Here's some of the code that's working wrong:
activeProject() {
let proj = { ...this.$store.state.activeProject };
if (proj.Start) {
debugger;
proj.Start = moment(proj.Start).format("MM/DD/YYYY");
proj.End = moment(proj.End).subtract(1, "days").format("MM/DD/YYYY");
return proj;
} else return {};
},
proj.Start = "2021-03-01T00:00:00.000Z"
outputs 02/28/2021
proj.End = "2021-03-08T00:00:00.000Z"
outputs 03/06/2021
So after formatting with moment, it takes 1 days off of proj.Start
and proj.End
. Why would it be doing this?
Upvotes: 2
Views: 607
Reputation: 33933
In the ISO 8601 standard, the Z
means UTC (Coordinated Universal Time), which in practice is London, England Time.
Your issue is reproduced below if you are in a timezone west of London, England (like me) and the current time time in London just passed 00:00 (like right now as I write this answer). That snippet would ouput the right values for one being in a timezone East of London, at the same moment.
let proj = {Start: "2021-03-01T00:00:00.000Z", End:"2021-03-08T00:00:00.000Z"}
proj.Start = moment(proj.Start).format("MM/DD/YYYY");
proj.End = moment(proj.End).subtract(1, "days").format("MM/DD/YYYY");
console.log(proj.Start, "expected: 03/01/2021")
console.log(proj.End, "expected: 03/07/2021")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Notice without the Z
now...
let proj = {Start: "2021-03-01T00:00:00.000", End:"2021-03-08T00:00:00.000"}
proj.Start = moment(proj.Start).format("MM/DD/YYYY");
proj.End = moment(proj.End).subtract(1, "days").format("MM/DD/YYYY");
console.log(proj.Start, "expected: 03/01/2021")
console.log(proj.End, "expected: 03/07/2021")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
So your issue is specififying a date/time relative to UTC while it seems it is not what you want.
Your solution would be to remove the final Z
from the data used...
moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.
Upvotes: 1