Skip to content

Instantly share code, notes, and snippets.

@bricksroo
Last active August 17, 2021 23:49
Show Gist options
  • Save bricksroo/221766280f7b9e59fc279679050686af to your computer and use it in GitHub Desktop.
Save bricksroo/221766280f7b9e59fc279679050686af to your computer and use it in GitHub Desktop.
Checking day for weekday or weekend ordinal (ie. first weekend day or third weekday).
// imports from date-fns https://github.com/date-fns/date-fns
const isWeekend = require('date-fns/is_weekend');
const endOfMonth = require('date-fns/end_of_month');
const startOfDay = require('date-fns/start_of_day');
const startOfMonth = require('date-fns/start_of_month');
const addDays = require('date-fns/add_days');
const subDays = require('date-fns/sub_days');
// test day
const now = new Date(2018,1,28);
const obj = {
weekdayWeekend: (pattern, ordinal) => {
const ordinals = ['first', 'second', 'third', 'fourth'];
let checkDay;
const patterns = {
weekend_day: (checkDay) => isWeekend(checkDay),
weekday: (checkDay) => !isWeekend(checkDay),
}
// if looking for last, loop from end of month backwards
if (ordinal === 'last') {
// set check day to last day of month
checkDay = endOfMonth(now);
// set endDate for loop
endDate = endOfMonth(now).getDate();
for (let i = endDate; i >= endDate - 6; i -= 1) {
// if day matches weekend/weekday pattern
if (patterns[pattern](checkDay)) {
// set time to start of day for checking and end for loop
checkDay = startOfDay(checkDay);
break;
}
// otherwise, step back a day in loop
checkDay = subDays(checkDay, 1);
}
// otherwise, loop from start of month forward
} else {
// set check day to first day of month
checkDay = startOfMonth(now);
// set count to account for ordinals
count = 0;
// for loop from start of month forwards
for (let i = 1; i <= 14; i += 1) {
// if day matches weekend/weekday pattern
if (patterns[pattern](checkDay)) {
// if count matches with ordinal index in array
if (ordinals.indexOf(ordinal) === count) {
break;
}
// if ordinal doesnt match, but weekday/weekend does increase count by one
count += 1;
}
// otherwise, step forward a day in loop
checkDay = addDays(checkDay, 1);
}
}
// return boolean for matching given date and actual
return checkDay.getTime() === now.getTime();
}
}
console.log('test', obj.weekdayWeekend('weekday','last'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment