简体   繁体   中英

How to convert date from one timezone to another timezone

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM