Skip to content

Is there a way to preserve the timezone offset from an ISO 8601 string? #74

Description

@duandz-eh

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions