Native timezone support vs. date-fns-tz #3904
-
Are there any differences or benefits of using the new native timezone support in companion with const timezone = 'CET'
const from = parseISO('2024-11-30T23:00:00.000Z')
// date-fns-tz
const endOfDay = fromZonedTime(endOfDay(toZonedTime(from, timezone)), timezone)
// @date-fns/tz
const endOfDay = new TZDate(endOfDay(new TZDate(from, 'UTC').withTimeZone(timezone)), timezone).withTimeZone('UTC') Or do I miss something here on the new API? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey! I think you missed it, but the date-fns functions do return the date in the same type as you pass inside: const date = startOfMinute(endOfDay(new TZDate(from, timezone)));
date.toString();
//=> 'Sun Dec 01 2024 23:59:00 GMT+0100 (GMT+01:00)'
date instanceof TZDate;
//=> true Additionally, I don't think the code does what you think it should. In the const timezone = "CET";
const from = parseISO("2024-11-30T23:00:00.000Z");
//=> '2024-11-30T23:00:00.000Z'
const zonedFrom = toZonedTime(from, timezone);
//=> '2024-11-30T16:00:00.000Z'
const eod = endOfDay(zonedFrom);
//=> '2024-12-01T15:59:59.999Z'
const fromZoned = fromZonedTime(eod, timezone);
//=> '2024-12-01T22:59:59.999Z' With date-fns to achieve that, you would use import { transpose } from "date-fns";
import { tz } from "@date-fns/tz";
// Singapore is the system time zone:
const sgDate = new Date(2024, 8 /* Sep */, 7, 6, 5, 4);
//=> 'Wed Sep 07 2024 06:05:04 GMT+0800 (Singapore Standard Time)'
// Transpose the date to Los Angeles time zone:
const laDate = transpose(sgDate, tz("America/Los_Angeles"));
//=> 'Wed Sep 07 2024 06:05:04 GMT-0700 (Pacific Daylight Time)'
// Transpose back to local time zone using Date:
const systemDate = transpose(laDate, Date);
//=> 'Wed Sep 07 2024 06:05:04 GMT+0800 (Singapore Standard Time)' The function is helpful when for example you get your date from a date picker but you want to have the same values in a different time zone that comes from settings. However, in your case, it's not needed at all. To get the end of the day in the given time zone, you don't need to do anything extra: const timezone = "CET";
const from = parseISO("2024-11-30T23:00:00.000Z");
//=> '2024-11-30T23:00:00.000Z'
const eod = endOfDay(new TZDate(from, timezone));
//=> '2024-12-01T23:59:59.999+01:00' You might notice that I think I'm missing something, as these calculations are a bit extra, and I don't know what you want to achieve by converting it to UTC. If you tell me more, I might be able to help you further. |
Beta Was this translation helpful? Give feedback.
Hey!
I think you missed it, but the date-fns functions do return the date in the same type as you pass inside:
Additionally, I don't think the code does what you think it should. In the
@date-fns/tz
callingwithTimeZone
and passing"UTC"
does nothing but convert the time zone without changing the timestamp, whilefromZonedTime
andtoZonedTime
do change it: