marnusw / date-fns-tz

Complementary library for date-fns v2 adding IANA time zone support

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Working with UTC is messed up

bmakan opened this issue · comments

What are the UTC functions supposed to do? Because they don't do what I expect them to. Actually, none of the functions I tried do what is described they should do.

Europe/Bratislava is currently UTC+2.

const isoDate = '2023-04-21 06:04:23';

console.log(zonedTimeToUtc(isoDate , 'Europe/Bratislava'));
Fri Apr 21 2023 06:04:23 GMT+0200 (Central European Summer Time)
// Expected: 2023-04-21 04:04:23
// Reasoning: input is in the specified time zone, so I expect the output to be in the UTC

console.log(utcToZonedTime(isoDate , 'Europe/Bratislava'));
Fri Apr 21 2023 06:04:23 GMT+0200 (Central European Summer Time)
// Expected: 2023-04-21 08:04:23
// Reasoning: input is in UTC, so I expect the output to be in the specified time zone

They both return the exact same date in my local time zone. I understand my local time zone will always be there internally - it's how JS works. But I would expect the date values to be set to either UTC or my target timezone.

So, again, what are these functions supposed to do?

I found the cause of this behavior.

const isoDate = '2023-04-21 06:04:23';

My date here doesn't have the time zone info. It's missing the Z at the end indicating it's in the UTC (as described in ISO 8601). Once I add it, it works as expected.

const isoDate = '2023-04-21 06:04:23Z';
'2023-04-21 06:04:23Z'

utcToZonedTime(isoDate, 'Europe/Bratislava')
Fri Apr 21 2023 08:04:23 GMT+0200 (Central European Summer Time)

utcToZonedTime(isoDate, 'Europe/Athens')
Fri Apr 21 2023 09:04:23 GMT+0200 (Central European Summer Time)

Closing. Hopefully this helps others with the same issue.