Reputation: 14129
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.
Upvotes: 3
Views: 2066
Reputation: 443
Anyone looking for a solution in 2024, it seems that zonedTimeToUtc()
is no longer available in date-fns-tz
. You can use formatInTimeZone()
instead:
import { formatInTimeZone } from 'date-fns-tz'
const date = new Date('2024-05-06T10:46:20Z')
formatInTimeZone(date, 'Africa/Casablanca', 'yyyy-MM-dd HH:mm:ss')
//output: 2024-05-06 11:46:20
Upvotes: 0
Reputation: 241460
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.
Upvotes: 3