Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a TZDate instance from an IsoString with offset #41

Open
gbalduzzi opened this issue Jan 16, 2025 · 1 comment
Open

Create a TZDate instance from an IsoString with offset #41

gbalduzzi opened this issue Jan 16, 2025 · 1 comment

Comments

@gbalduzzi
Copy link

From an external service, I receive time strings in the iso format, containing the timezone offset:

2024-09-12T00:00:00Z+02:00
2024-09-12T00:00:00Z-05:00

date-fns parseIso correctly process the timezone, but converts the Date into the browser timezone.

Is there a way to obtain a proper TZDate instance from such an isoString?

In the documentation I can only see ways to build a TZDate when you already know the desidered timezone in advance

@jonathanstanley
Copy link

jonathanstanley commented Jan 26, 2025

I had the same question and couldn't find a solution in the docs. @date-fns Is there a reason there isn't a function like this?

/** returns a TZDate using the timezone of the ISO 8601 string */
export const parseWithTz = (iso: string) => {
  const offset = iso.match(/([-+])(\d{2}):(\d{2})$/)?.at(0);
  return new TZDate(iso, offset);
};

let example = "2024-01-12T01:10:10.110-06:00";
console.log(parseWithTz(example).toISOString()); // 2024-01-12T01:10:10.110-06:00 ✅ identical
console.log(new TZDate(example).toISOString()) // ❌ drops/loses original offset and outputs local/sys offset

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants