Get start of date passing a timezone using date-fns

Viewed 337

I need to use the startOfToday function for a specific timezone. For example, in my current timezone I get:

// In my browser, staying at 'Europe/Madrid' timezone
Intl.DateTimeFormat().resolvedOptions().timeZone // 'Europe/Madrid' (Zone +0100)

startOfDay(
  new Date()
) // Tue Mar 01 2022 00:00:00 GMT+0100 (Central European Standard Time)
/*
                                   /\
                                   ||
                                   ||

                       Obtained +0100 (Europe/Madrid)
*/

I get the start of date in my current timezone, how can I pass a a timezone to calculate the current start of day in that timezone? Im looking for something like:

// In my browser, staying at 'Europe/Madrid' timezone
Intl.DateTimeFormat().resolvedOptions().timeZone // 'Europe/Madrid' (Zone +0100)

startOfDay(
  new Date(),
  'America/Toronto'
) // Tue Mar 01 2022 00:00:00 GMT-0500 (Central European Standard Time)
/*
                                   /\
                                   ||
                                   ||

                      Should be -0500 (America/Toronto)
*/
1 Answers

I managed to make it work using date-fns-tz package:

import { startOfDay } from "date-fns";
import { utcToZonedTime } from "date-fns-tz";

const date = new Date("2022-03-01T04:00:00.000Z") // Tue Mar 01 2022 05:00:00 GMT+0100
const timeZone = "America/Toronto"
const zonedDate = utcToZonedTime(date, timeZone) // Mon Feb 28 2022 23:00:00 GMT+0100
const startOfDateInZonedTime = startOfDay(zonedDate).toISOString() // 2022-02-27T23:00:00.000Z
Related