Skip to content

Instantly share code, notes, and snippets.

@naosim
Created March 23, 2023 00:15
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 naosim/7a368b507b5e87115ee67624ee21ad84 to your computer and use it in GitHub Desktop.
Save naosim/7a368b507b5e87115ee67624ee21ad84 to your computer and use it in GitHub Desktop.
営業日ベースでn日後の日付を計算する
function addBusinessDays(date, daysToAdd, holidays) {
// weekends: 0 = Sunday, 6 = Saturday
const weekendDays = [0, 6];
// create a set of holidays for O(1) lookup time
const holidaySet = new Set(holidays.map((holiday) => holiday.getTime()));
let businessDaysAdded = 0;
let currentDate = new Date(date.getTime());
while (businessDaysAdded < daysToAdd) {
// add one day to the current date
currentDate.setDate(currentDate.getDate() + 1);
// check if the current date is a weekend or holiday
const currentDay = currentDate.getDay();
const isWeekend = weekendDays.includes(currentDay);
const isHoliday = holidaySet.has(currentDate.getTime());
// if it's not a weekend or holiday, count it as a business day added
if (!isWeekend && !isHoliday) {
businessDaysAdded++;
}
}
return currentDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment