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

Inconsistent format behavior #10

Open
allohamora opened this issue Sep 23, 2024 · 1 comment
Open

Inconsistent format behavior #10

allohamora opened this issue Sep 23, 2024 · 1 comment

Comments

@allohamora
Copy link
Contributor

date-fns-tz

import { format } from 'date-fns-tz';

// '2023-03-20T11:11:00-04:00'
format(new Date('2023-03-20T11:11:00'), "yyyy-MM-dd'T'HH:mm:ssXXX", { timeZone: 'America/New_York' });

@date-fns/tz

import { tz } from '@date-fns/tz';
import { format } from 'date-fns';

// '2023-03-20T05:11:00-04:00' (my timeZone -02:00)
format(new Date('2023-03-20T11:11:00'), "yyyy-MM-dd'T'HH:mm:ssXXX", { in: tz('America/New_York') });

How to get the date-fns-tz behavior with @date-fns/tz?

@camsteffen
Copy link

When you write format(..., { timeZone: '...' }), this means use the local time of the Date that I provide but ignore it's absolute time because it is probably wrong. But when you write anyFunction(... { in: ... }) it means use the absolute time of the Date I give you and translate it to the specified timezone. date-fns 4 removes the need for such "Dates with probably wrong absolute time", but you will need to change the way that you construct the Date. When you write new Date('2023-03-20T11:11:00'), that Date will be in the local system timezone. That is the smoking gun.

To create a proper Date for your use case, you can write:

const betterDate = parseISO('2023-03-20T11:11:00', { in: tz('America/New_York') });

...and then when you format it, you don't need to specify a timezone:

format(betterDate, "yyyy-MM-dd'T'HH:mm:ssXXX");

So, at a high level, I would say date-fns 4 encourages you to make the date object responsible for its timezone instead of the format function.

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