Last active
January 23, 2024 07:11
-
-
Save trvswgnr/59c6c31f85e689385fc56e21ba4027b2 to your computer and use it in GitHub Desktop.
check if a date is within dst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isDST(date: Date, timeZone: string = 'America/New_York'): boolean { | |
const year = date.getFullYear(); | |
const startDST = getNthDayOfMonth(2, 0, 2, year); // sec sun in mar | |
const endDST = getNthDayOfMonth(1, 0, 10, year); // first sun in nov | |
const localDate = new Date(date.toLocaleString('en-US', { timeZone })); | |
const utcOffset = localDate.getTimezoneOffset() * 60000; // in milliseconds | |
const utcDate = new Date(localDate.getTime() + utcOffset); | |
return utcDate >= startDST && utcDate < endDST; | |
} | |
function getNthDayOfMonth(nth: number, day: number, month: number, year: number): Date { | |
const date = new Date(year, month, 1); | |
const add = (day - date.getDay() + 7) % 7 + (nth - 1) * 7; | |
date.setDate(1 + add); | |
return new Date(Date.UTC(year, month, date.getDate(), 2)); // 2am local time in UTC | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment