You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 directlyconstdateString="2024-04-03";constformattedDateString=format(dateString,"yyyy-MM-dd");console.log(formattedDateString);// Outputs "2024-04-03"// Creating a Date object and formatting itconstdateObject=newDate(2024,3,3);// Note: JavaScript months are 0-basedconstformattedDateObject=format(dateObject,"yyyy-MM-dd");console.log(formattedDateObject);// Outputs "2024-04-03"
Could you please provide more detailed information about the problem?
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.
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.
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.
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
The text was updated successfully, but these errors were encountered: