Skip to content

Instantly share code, notes, and snippets.

@mattc41190
Last active April 14, 2021 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattc41190/0496ee96656041eb95c409e1d8b10863 to your computer and use it in GitHub Desktop.
Save mattc41190/0496ee96656041eb95c409e1d8b10863 to your computer and use it in GitHub Desktop.
When is Thanksgiving and Why?
// Problem Statement:
// Find out how to calculate Thanksgiving in a given year
// Credits: https://coffeescript-cookbook.github.io/chapters/dates_and_times/date-of-thanksgiving
// SOLUTION:
const isDateInPast = (_date) => {
const now = new Date()
const nowInt = Date.parse(now)
const dateInt = Date.parse(_date)
return nowInt - dateInt > 0
}
const getThanksgiving = (year, nextYear) => {
const getThanksgivingForYear = (y) => {
const firstDayOfNovember = new Date(`11/1/${y}`)
const dayOfWeekNovemberFirst = firstDayOfNovember.getDay()
const thanksgivingDay = 22 + ((11 - dayOfWeekNovemberFirst) % 7)
return new Date(`11/${thanksgivingDay}/${y}`)
}
const currentYearThanksGiving = getThanksgivingForYear(year)
const nextYearThanksGiving = getThanksgivingForYear(nextYear)
const thanksgiving = isDateInPast(currentYearThanksGiving)
? nextYearThanksGiving
: currentYearThanksGiving
return thanksgiving
}
let t = getThanksgiving(2021, 2022)
console.log(t)
// My question:
// Why is 11 the magic number?
// Sunday = 0 (4 days till Thursday) (---) 11 - 0 == 11 (---) 11 % 7 == 4
// Monday = 1 (3 days till Thursday) (---) 11 - 1 == 10 (---) 10 % 7 == 3
// Tuesday = 2 (2 days till Thursday) (---) 11 - 2 == 9 (---) 9 % 7 == 2
// Wednesday = 3 (1 days till Thursday) (---) 11 - 3 == 8 (---) 8 % 7 == 1
// Thursday = 4 (0 days till Thursday) (---) 11 - 4 == 7 (---) 7 % 7 == 0
// Friday = 5 (6 days till Thursday) (---) 11 - 5 == 6 (---) 6 % 7 == 6
// Saturday = 6 (5 days till Thursday) (---) 11 - 6 == 5 (---) 5 % 7 == 5
// Of Note:
// Thursday = 4 (0 days till Thursday) (---) 11 - 4 == 7
// AND (drum roll...) 7 % 7 == 0!
// 11 is the number for which the "day" of the week mods perfectly into 7 (i.e. leaves no remainder)
// For this reason the earliest day of month possible is November 22nd (November started on Thursday)
// and the last date possible is November 28th (November started on Friday)
@mattc41190
Copy link
Author

SEO Maybe 🤷‍♀️: How to calculate or find thanksgiving in Javascript with explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment