Calculate previous working day excluding weekends and federal holidays in JavaScript

后端 未结 2 455
暖寄归人
暖寄归人 2021-01-27 07:02

I am writing a function which will provide me previous working day for any given date. Working day means it is a weekday and there\'s no federal holiday on that day.

My

2条回答
  •  一向
    一向 (楼主)
    2021-01-27 07:27

    You are not using Luxon to its full potential. You should leave the date as a Luxon object, do all the operations on it using Luxon's methods, and then convert the date into a string.

    To do that, I defined a helper function prevBusinessDayHelper that takes a Luxon datetime and returns a date time representing the previous business day. It operates entirely in terms of Luxon datetimes, which makes it easy. Then in the outer function, I convert to and from Luxon datetimes.

    const DateTime = luxon.DateTime;
    
    // use a Set to make lookups cheaper
    const federalHolidays = new Set([
      '2019-05-27', // <-- you were missing the 0 here in yours
      '2019-09-02',
      // snip
    ]);
    
    // recursion is good here because it's very shallow
    const prevBusinessDayHelper = dt => {
    
      // use luxon's tools!
      const yest = dt.minus({ days: 1 });
    
      if (yest.weekday == 6 || yest.weekday == 7 || federalHolidays.has(yest.toISODate()))
        return prevBusinessDayHelper(yest);
    
      return yest;
    };
    
    const prevBusinessDay = (isoString, zone) => {
      const dt = DateTime.fromISO(isoString).setZone(zone);
      return prevBusinessDayHelper(dt).toISODate();
    };
    
    console.log(prevBusinessDay("2019-05-28T07:00:00.000Z", "America/New_York"));

提交回复
热议问题