Start of day in a given timezone. #2853
Replies: 2 comments
-
Nevertheless, here's the best I can come up with for the current state of the library ( 1) Node.js If you're using Node, you can temporarily change the system's local timezone and use the import { startOfDay } from 'date-fns';
const defaultTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const d = new Date(Date.UTC(2021, 0, 1, 21));
console.log(d.toISOString()); // 2021-01-01T21:00:00.000Z
process.env.TZ = 'Australia/Perth';
const res = startOfDay(d);
console.log(res.toISOString()); // 2021-01-01T16:00:00.000Z
// reset timezone
process.env.TZ = defaultTimeZone; 2) Browser - user already in target timezone If you're in the browser and 'Australia/Perth' is already the user's local time zone, then the above will also work and you don't need to manually juggle timezones (just remove all the process.env.TZ stuff). import { startOfDay } from 'date-fns';
const d = new Date(Date.UTC(2021, 0, 1, 21));
console.log(d.toISOString()); // 2021-01-01T21:00:00.000Z
const res = startOfDay(d);
console.log(res.toISOString()); // 2021-01-01T16:00:00.000Z 3) Browser - user not in target timezone It gets really tricky if your user is in a different timezone though. You also need to use the Use the following at your own risk... import { format, getTimezoneOffset } from "date-fns-tz";
const d = new Date(Date.UTC(2021, 0, 1, 21));
console.log(d.toISOString()); // 2021-01-01T21:00:00.000Z
const timeZone = "Australia/Perth";
// compensate the tz offset manually so we end up on the correct date
const offset = getTimezoneOffset(timeZone, d);
const dOffset = new Date(d.getTime() + offset);
console.log(dOffset.toISOString()); // 2021-01-02T05:00:00.000Z
// build a string that represents midnight for target timezone
const str = format(dOffset, `yyyy-MM-dd'T'00:00:00xxx`, { timeZone });
console.log(str); // 2021-01-02T00:00:00+08:00
// build final date object
const startOfDayInPerth = new Date(str);
console.log(startOfDayInPerth.toISOString()); // 2021-01-01T16:00:00.000Z |
Beta Was this translation helpful? Give feedback.
-
Following @fturmel's suggestion, here's how you do it using the library
|
Beta Was this translation helpful? Give feedback.
-
How do I get the start of the day in a given timezone?
For example, if I had a date object
x
representing Jan 1 9pm GMT, thenx.startOfDayInTimeZone("Australia/Perth")
should be Jan 1 4pm GMT, as "Australia/Perth" is GMT+8.Beta Was this translation helpful? Give feedback.
All reactions