Sometimes it is required to check if a certain date is a public holiday or day in the weekend.
If it is the case then you might be interested in adding enough days to make sure the date is a "normal" working day.
We can use the following JavaScript snippet to perform such check.
Utility class (file saved as DateUtil.js):
const holidays = { "0,1": "public holiday 1", "3,15": "public holiday 2", "3,17": "public holiday 3", "3,18": "public holiday 4", "6,13": "public holiday 5", "6,14": "public holiday 6", "6,15": "public holiday 7", }; class DateUtil { static #isWeekend(date) { const dayOfWeek = date.getDay(); return (dayOfWeek === 6) || (dayOfWeek === 0); } static #isPublicHoliday(date) { return !!holidays[date.getMonth() + ',' + date.getDate()]; } static isWeekendOrPublicHoliday(date) { return this.#isPublicHoliday(date) || this.#isWeekend(date); } } module.exports = {DateUtil}
Using the utility class (file saved as is-weekend-or-public-holiday.js):
const {DateUtil} = require('./DateUtil') let date = new Date(); date.setDate(date.getDate() + 30); console.log(`${date} is weekend or public holiday: ${DateUtil.isWeekendOrPublicHoliday(date)}`) while (DateUtil.isWeekendOrPublicHoliday(date)) { date.setDate(date.getDate() + 1); } console.log(`${date} is weekend or public holiday: ${DateUtil.isWeekendOrPublicHoliday(date)}`)
Example output (run code with: node path/to/is-weekend-or-public-holiday.js):
Wed Jul 13 2022 16:17:09 GMT+0200 (Central European Summer Time) is weekend or public holiday: true Mon Jul 18 2022 16:17:09 GMT+0200 (Central European Summer Time) is weekend or public holiday: false
You only need to define the set of public holidays that applies to your country.
Delen: