How to convert date from one timezone to another timezone

1.5k views Asked by At

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.
1

There are 1 answers

0
Matt Johnson-Pint On BEST ANSWER

To get time zone support for date-fns, you will need the date-fns-tz add-on module.

Then you can do the following:

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

const dt = zonedTimeToUtc('2020-10-13', 'America/Chicago');

The result will be a Date object that represents midnight in the given time zone.

Keep in mind that Date objects themselves are always UTC-based. Thus, you can't get a Date object that is "in" a different time zone.

Also, you should pass a string into the zonedTimeToUtc function as shown. You should not pass it to the Date object. 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 the Date object constructor.