Hi, I'm wondering if there's a built-in way in @date-fns/tz to construct a TZDate that automatically retains the UTC offset already present in an ISO string input.
Input
const input = "2024-09-12T15:09:02.743+03:00";
Expected output
date.timeZone; // => "+03:00"
format(date, "dd/MM/yyyy HH:mm:ss xxx"); // => "12/09/2024 15:09:02 +03:00"
What I tried
Passing the string directly without a timezone, it falls back to the system timezone and loses the original offset:
const date = new TZDate("2024-09-12T15:09:02.743+03:00");
date.timeZone; // => undefined
date.toString(); // => "Thu Sep 12 2024 12:09:02 GMT+0000 (Coordinated Universal Time)"
format(date, "dd/MM/yyyy HH:mm:ss xxx"); // => "12/09/2024 12:09:02 +00:00"
Manually extracting the offset and passing it explicitly, this works but feels like boilerplate I'd expect the library to handle:
const getTimezoneOffset = (dateStr: string): string => {
if (dateStr.at(-1) === 'Z') return '+00:00';
return dateStr.match(/[+-]\d{2}:?\d{2}$/)?.[0] ?? 'UTC';
};
const date = new TZDate(input, getTimezoneOffset(input));
format(date, "dd/MM/yyyy HH:mm:ss xxx"); // => "12/09/2024 15:09:02 +03:00"
Is there a cleaner or more idiomatic way to do this with the library? Or is manually extracting the offset the intended approach? Thanks!
Environment
@date-fns/tz version: 1.4.1
date-fns version: 4.1.0
Hi, I'm wondering if there's a built-in way in
@date-fns/tzto construct aTZDatethat automatically retains the UTC offset already present in an ISO string input.Input
Expected output
What I tried
Passing the string directly without a timezone, it falls back to the system timezone and loses the original offset:
Manually extracting the offset and passing it explicitly, this works but feels like boilerplate I'd expect the library to handle:
Is there a cleaner or more idiomatic way to do this with the library? Or is manually extracting the offset the intended approach? Thanks!
Environment
@date-fns/tzversion: 1.4.1date-fnsversion: 4.1.0