I have a date which is the beginning of a given day in the user's browser timezone but I need to convert it to the beginning of the day in another timezone, using date-fns.
I have a date:
const date = new Date("2020-10-13"); // Tue Oct 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
And I need to convert it to the beginning of the day in the "America/Chicago" timezone.
const timeZone = "America/Chicago";
// Need to convert a date object
// Tue Oct 13 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
// to
// Tue Oct 13 2020 00:00:00 GMT-0500 (Central Daylight Time)
// and all I'm given is the timeZone value.
To get time zone support for date-fns, you will need the date-fns-tz add-on module.
Then you can do the following:
The result will be a
Dateobject that represents midnight in the given time zone.Keep in mind that
Dateobjects themselves are always UTC-based. Thus, you can't get aDateobject that is "in" a different time zone.Also, you should pass a string into the
zonedTimeToUtcfunction as shown. You should not pass it to theDateobject. As mentioned in comments, the ECMAScript spec says that a date-only string value should be parsed as UTC. However, there are still some implementations that don't follow the spec correctly. Thus, you should avoid parsing strings using theDateobject constructor.