Skip to content

Instantly share code, notes, and snippets.

@EB-Plum
Created July 7, 2022 03:57
Show Gist options
  • Select an option

  • Save EB-Plum/afb237600a7c80b6ccc276bf8346596b to your computer and use it in GitHub Desktop.

Select an option

Save EB-Plum/afb237600a7c80b6ccc276bf8346596b to your computer and use it in GitHub Desktop.
get date of N-th X-day in specific Year-Month
/*
get date of N-th X-day in specific Year-Month
logic behind first_x_day_date
xday
0 1 2 3 4 5 6
getDay 0 | 1 2 3 4 5 6 7
(wday) 1 | 7 1 2 3 4 5 6
2 | 6 7 1 2 3 4 5
3 | 5 6 7 1 2 3 4
4 | 4 5 6 7 1 2 3
5 | 3 4 5 6 7 1 2
6 | 2 3 4 5 6 7 1
when getDay is 0, result is just => xday+1
as getDay increase, result is slide off by getDay => xday+1 - getDay
but, date should not be negative so add 7 and get remain => (xday+1-getDay + 7) % 7
but, remain makes 7 to 0, so using IF or OR to make 0 to 7 again => (xday+1-getDay+7)%7 || 7
WARN: may not same as Month's Nth week's weekday, it just consider Nth occuring weeday
WARN: input validation not included
WARN: 5th weekday may not exist or not, not concerned yet
*/
function nthXdayDate(year, month, nth, xday) {
// year = YYYY
// month = 1~12
// nth = 1~5 ?
// xday = 0~6 (SUN ~ SAT)
const first_date_wday = new Date(year, month - 1).getDay()
const first_xday_date = (8 + xday - first_date_wday) % 7 || 7
const nth_xday_date = first_xday_date + (nth - 1) * 7
return nth_xday_date
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment