Edit: My local timezone is UTC+1
-
I have this date string:
2024-07-01T00:00:00.000Z
. -
This date string has a
'Z'
at the end which denotes that it is in UTC (If I understand correctly).
When I run
moment('2024-07-01T00:00:00.000Z').toISOString()
-> '2024-07-01T00:00:00.000Z' // returns
Cool, that’s what I expect.
But when I want to get the start of that day for that moment object:
moment('2024-07-01T00:00:00.000Z').startOf('day').toISOString();
=> '2024-06-30T23:00:00.000Z' // returns
Question: Why is it returning an hour earlier, shifting a day behind my original date which was denoted in UTC?
I suspect that it has to do with my UTC offset of +1. It is for some reason, assuming that '2024-07-01T00:00:00.000Z'
is 1 hour ahead of UTC?
Many thanks!
Btw, my moment version is 2.29.4
2
Answers
By default, moment parses and displays in local time. If you want to parse date as UTC, you have use
moment.utc
. If you want to pass offset in time, then you need to usemoment.parseZone
that will resolve to UTC if no offset given. You can also switch between UTC and local mode calling.local
and.utc
on your instance. And if you want to check if you are working with UTC date or not, you can callcreationData().isUTC
that will give you current mode.You are in a time zone one hour ahead of UTC. So if you do
You are parsing the given timestamp (where the
Z
defines it is in UTC to a instance ofmoment
. As you are in UTC+1 and moment uses localtime per default, this is2024-07-01T01:00:00
in your localtime.When you now do
.startOf('day')
you are going to the start of the day2024-07-01T00:00:00.000
, again in local time. And finally.toISOString()
creates a UTC representation of this timestamp, which is of course2024-06-30T23:00:00.000Z
If you want your resulting moment instance to be in UTC, use
moment.utc(...)
instead.Btw: momentjs is considered deprecated and is not maintained anymore and its authors suggest to not use it in new projects anymore.