Last active
January 18, 2022 14:40
-
-
Save tjmoses/017edc562b2e747a19101a40832234c2 to your computer and use it in GitHub Desktop.
Javascript Holidays using built-in date function (static & floating)
This file contains 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 isHoliday(date: Date) { | |
const holidays = { | |
MD: { | |
// Month, Day | |
'1/1': "New Year's Day", | |
'7/4': 'Independence Day', | |
'11/11': "Veteran's Day", | |
'12/25': 'Christmas Day', | |
'12/31': "New Year's Eve" | |
}, | |
MODW: { | |
// Month, Occurence, Day of Week | |
'1/3/1': 'Martin Luther King Jr. Day', | |
'2/3/1': 'Presidents Day', | |
'5/L/1': 'Memorial Day', | |
'9/1/1': 'Labor Day', | |
'10/2/1': 'Columbus Day', | |
'11/4/4': 'Thanksgiving Day' | |
} | |
}; | |
const dayOfTheMonth = date.getDate(); | |
const month = date.getMonth() + 1; | |
const dayOfTheWeek = date.getDay(); // 0 - 6, Su -> Sa | |
const lastDayOfTheMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); | |
const isLastOccurrence = dayOfTheMonth + 7 > lastDayOfTheMonth; | |
let currentOccurrenceDay = dayOfTheMonth, | |
occurrence = 0; | |
for (currentOccurrenceDay; currentOccurrenceDay > 0; currentOccurrenceDay -= 7) occurrence++; | |
return !!( | |
holidays.MD?.[`${month}/${dayOfTheMonth}`] || | |
(isLastOccurrence && holidays.MODW?.[`${month}/L/${dayOfTheWeek}`]) || | |
holidays.MODW?.[`${month}/${occurrence}/${dayOfTheWeek}`] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment