Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript calculates The Date of Thanksgiving (in the United States and Canada).


May 09, 2021 CoffeeScript


Table of contents


Calculate the date of Thanksgiving (in the United States and Canada).

Problem

You need to find the month and date of Thanksgiving in the year given.

Solution

The following function returns the date of Thanksgiving for the year given. I f no parameters are given, the result is the current year.

Thanksgiving Day in the United States is the fourth Thursday in November.

thanksgivingDayUSA = (year = (new Date).getFullYear()) ->
  first = new Date year, 10, 1
  day_of_week = first.getDay()
  22 + (11 - day_of_week) % 7

Thanksgiving Day in Canada is on the second Monday in October.

thanksgivingDayCA = (year = (new Date).getFullYear()) ->
    first = new Date year, 9, 1
    day_of_week = first.getDay()
    8 + (8 - day_of_week) % 7

Discuss

thanksgivingDayUSA() #=> 24 (November 24th, 2011)

thanksgivingDayCA() # => 10 (October 10th, 2011)

thanksgivingDayUSA(2012) # => 22 (November 22nd)

thanksgivingDayCA(2012) # => 8 (October 8th)

The idea is simple:

  1. Find out which day is the first day of each of the following months (November, Canada October).
  2. Calculate the amount that is offset from that day to the next business day (Thursday in the United States, Monday in Canada).
  3. Add this offset to the first possible holiday date (22nd American Thanksgiving, 8th Canadian Thanksgiving).