Home > Back-end >  new Date(...).toISOString() in JavaScript gives incorrect result on one day of the year
new Date(...).toISOString() in JavaScript gives incorrect result on one day of the year

Time:07-16

I'm building a calendar and I noticed that the date is incorrect on one day of the year.

I wanted to standardize dates to ISO 8601. Let's take 2022-03-27 for example:

const foo = new Date(2022, 2, 27).toISOString()

This gives 2022-03-27T00:00:00.000Z as one would expect.

However, the next day, 2022-03-28:

const bar = new Date(2022, 2, 28).toISOString()

This gives 2022-03-27T23:00:00.000Z - 27th March at 23:00.

Why does this happen?

CodePudding user response:

What's happening is that British Summer Time (Daylight Saving Time, aka DST) is kicking in between your two examples (specifically, it starts at 01:00 on 2022-03-27). toISOString always gives you UTC time (GMT) as you can tell from the Z at the end of the string, but your local time is an hour ahead of UTC after 01:00 on 2022-03-27 until DST ends at 02:00 on 30 October 2022.

In your first example, you're creating a Date with the local time of midnight on 2022-03-27, when your local time is (apparently) GMT 00:00 (like mine here in the UK). So toISOString gives you back 00:00 because your local time is GMT/UTC (that date/time is an hour before DST kicks in).

But in your second example, you're creating a Date in local time at midnight on 2022-03-28, when you're on DST. So you're offset from UTC by an hour (UTC is one hour behind you). Midnight 2022-03-28 UK time is 23:00 2022-03-27 UTC.

I don't know what you want to do with this stuff, but if you want to create a Date for midnight UTC on 2022-03-28, use new Date(Date.UTC(2022, 2, 28)).

  • Related