Reputation: 12431
I'm trying to create a function which returns the start and end time for a given date and given timezone in UTC using dayjs
. These are examples of the results I think I need:
Date | Timezone | Start | End |
---|---|---|---|
2021-04-15 | America/New_York | 2021-04-15T04:00:00.000Z | 2021-04-16T03:59:59.999Z |
2021-03-27 | America/New_York | 2021-03-27T04:00:00.000Z | 2021-03-28T03:59:59.999Z |
2021-03-13 | America/New_York | 2021-03-13T05:00:00.000Z | 2021-03-14T04:59:59.999Z |
This is the function I have:
dayjs.extend(utc);
dayjs.extend(timezone);
export const getDayRange = (date, timezone = "America/New_York") => ({
start: dayjs.tz(date, timezone).startOf("day").utc().toISOString(),
end: dayjs.tz(date, timezone).endOf("day").utc().toISOString()
});
However, it doesn't output the results I expect and appears to be influenced by local time (since the offset with UTC shifts on the 28th of March which was the end of DST in the UK not New York). I've tried various combinations of the chained dayjs
command with varying results, none correct.
This feels like it should be something which is quite straightforward with dayjs
, not to mention a fairly common use-case. However, I'm struggling to get something to work.
codesandbox example with tests
Upvotes: 0
Views: 1625
Reputation: 12431
Turns out there have been some issues with timezones in dayjs
since version v.1.9.6. Fixes are expected in the next release (1.10.5?):
https://github.com/iamkun/dayjs/issues/1437
I was able to use moment instead (since the APIs are mostly the same) which resolved my issue:
export const getDayRange = (date, timezone = "America/New_York") => ({
start: moment.tz(date, timezone).startOf("day").toISOString(),
end: moment.tz(date, timezone).endOf("day").toISOString()
});
Upvotes: 0