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

In version 3.6.0, format() shifts day backwards with string input, e.g. format('2024-04-03', 'yyyy-MM-dd') shift day to "2024-04-02" #3764

Closed
weihe8892 opened this issue Apr 11, 2024 · 2 comments

Comments

@weihe8892
Copy link

In version 3.6.0, day shift when format with string as input, e.g. format('2024-04-03', 'yyyy-MM-dd') output as 2024-04-02

@sumodmatto
Copy link

@weihe8892

I was unable to reproduce the issue you mentioned in my environment. The following code returns "2024-04-03" as expected:

import { format } from 'date-fns';

// Formatting a string date directly
const dateString = "2024-04-03";
const formattedDateString = format(dateString, "yyyy-MM-dd");
console.log(formattedDateString); // Outputs "2024-04-03"

// Creating a Date object and formatting it
const dateObject = new Date(2024, 3, 3); // Note: JavaScript months are 0-based
const formattedDateObject = format(dateObject, "yyyy-MM-dd");
console.log(formattedDateObject); // Outputs "2024-04-03"

Could you please provide more detailed information about the problem?

@fturmel
Copy link
Member

fturmel commented Apr 17, 2024

If you pass a string to the format function, it will use the native Date constructor internally. You can easily encounter this pitfall when dealing with JS dates:

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format

This means that if you are in a time zone with a negative offset, you are constructing a date time that is the day before what you intended in local time. And since date-fns uses local time by default, the format function will output the day before.

CleanShot 2024-04-17 at 08 31 25@2x


If you need to parse a date-only string and treat it as local, the easiest ways would be to append "T00:00:00" to it, or to use the parseISO function before passing it to format. As @sumodmatto mentioned, creating the date with numerical inputs is also a common alternative: new Date(2024, 3, 3)

You can also make date-fns v3 operate in UTC by using the UTCDate companion package if that's what was intended.

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

3 participants