Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Last active January 23, 2024 07:11
Show Gist options
  • Save trvswgnr/59c6c31f85e689385fc56e21ba4027b2 to your computer and use it in GitHub Desktop.
Save trvswgnr/59c6c31f85e689385fc56e21ba4027b2 to your computer and use it in GitHub Desktop.
check if a date is within dst
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