Skip to content

Instantly share code, notes, and snippets.

@basperheim
Created September 14, 2021 14:54
Show Gist options
  • Save basperheim/e52184dc2a0a62a1c366ad28f8f72c7d to your computer and use it in GitHub Desktop.
Save basperheim/e52184dc2a0a62a1c366ad28f8f72c7d to your computer and use it in GitHub Desktop.
Use JavaScript to check if a date is currently DST
/**
* Daylight saving time then ends on the first Sunday in November,
* when clocks are moved back an hour at 2 a.m. local daylight time
* (so they will then read 1 a.m. local standard time). In 2021,
* DST begins on March 14 and ends on Nov. 7 in the U.S.
*
* Defaults to current date. Options are: `{ year: null, month: null, day: null }`
**/
const isDST = (options = { year: null, month: null, day: null }) => {
const d = new Date();
const currentYear = d.getFullYear();
const currentMonth = d.getMonth();
const currentDay = d.getDate();
const targetYear = options.year || currentYear;
const targetMonth = options.month || currentMonth;
const targetDay = options.day || currentDay;
const currentDate = new Date(Date.UTC(targetYear, targetMonth, targetDay));
console.log(`\nisDST() currentDate: ${currentDate}`);
// console.log(`currentMonth: ${currentMonth}`);
// console.log(`targetDay: ${targetDay}`);
// all dates in April - Oct is DST
if (targetMonth > 2 && targetMonth < 10) {
return true;
}
// all dates from Dec - Feb is NOT DST
if (targetMonth > 10 || targetMonth < 2) {
return false;
}
// ..is month of November
else if (targetMonth === 10) {
let endDST = 1;
for (let day = 1; day < 20; day++) {
const novDate = new Date(Date.UTC(targetYear, 10, day)); // November
const dayOfWeek = novDate.getDay(); // returns day-of-week number (e.g. 2 == "Tuesday")
// 0 == "Sunday"
if (dayOfWeek === 0) {
endDST = day;
break;
}
}
// console.log(`endDST: ${endDST}`);
if (targetDay >= endDST) {
return false; // is NOT DST if after first Sun in Nov
} else {
return true;
}
}
// ..is month of March
else if (targetMonth === 2) {
let startDst = 1;
for (let day = 1; day < 32; day++) {
const marchDate = new Date(Date.UTC(targetYear, 2, day)); // March
const dayOfWeek = marchDate.getDay(); // returns day-of-week number (e.g. 2 == "Tuesday")
// 0 == "Sunday"
if (dayOfWeek === 0) {
startDst = day + 7; // needs to be 2nd Sunday of the month
break;
}
}
// console.log(`startDst: ${startDst}`);
if (targetDay >= startDst) {
return true; // is DST if mid-March or later
} else {
return false;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment