仅在本机js中从Date减去周末和公共假期

时间:2018-12-06 10:01:14

标签: javascript

我的任务是从任何给定日期减去x个周末和公众假期。来自Python背景,我将使用workalendar在五分钟内解决此问题。我目前正在为此抓挠头。

目标

该脚本将与日期选择器一起使用。用户将选择一个工作日,并将通知用户前x个工作日。可视化

sessions['SessionStartDate'] = sessions['SessionStartDate'].dt.date
out = (sessions.sort_values('SessionStartDate')
               .drop_duplicates(['DeviceID', 'SessionStartDate'])
               .groupby('DeviceID')['SessionStartDate']
               .apply(list))
print (out)
DeviceID
1    [2017-04-03, 2017-04-05]
2    [2017-04-04, 2017-04-06]
Name: SessionStartDate, dtype: object

语言环境是英国,我正在使用Gov.uk bank holidays json来获取公共假期,因为脚本需要考虑替代性的公共假期。

问题

当前,我正在使用这种逻辑

|------------|
| datepicker |
| 18/12/06   |
|------------|
x working days before: y
x working days before: y

这将产生以下输出

    while (!foundFour) {
        if (dayOfWeek === 0 || dayOfWeek === 6 || bankHolidays.includes(dateString)) {
            alert('The day you\'ve selected falls on either a weekend or a bank holiday. Please select a working day.');
        } else {
                    while(!foundFour) {
                        if (!foundFour) {
                            fourDays = new Date(startDate - counter * oneDay);
                            if (fourDaysDow !== 0 || fourDaysDow !== 6 || !bankHolidays.includes(fourDaysStr)) {
                                workingDays++;
                                var fourDaysDow = fourDays.getDay()

                                fourDaysY = startDate.getFullYear()
                                fourDaysM = zeroPad(startDate.getMonth() + 1, 2)
                                fourDaysD = zeroPad(startDate.getDate(), 2)
                                fourDaysStr =  fourDaysY + '-' + fourDaysM + '-' + fourDaysD

                                if (workingDays === 4) {
                                    foundFour = true;
                                }
                            } else {
                                fourDays.setDate(fourDays.getDate() -1);
                            }
                }
                counter++
                console.log(fourDays)
            } 
        }
    }

预期输出为

Date 2018-12-05T00:00:00.000Z   
Date 2018-12-04T00:00:00.000Z      
Date 2018-12-03T00:00:00.000Z  
Date 2018-12-02T00:00:00.000Z

我看不出问题出在哪里。完整脚本供参考

Date 2018-12-05T00:00:00.000Z   
Date 2018-12-04T00:00:00.000Z      
Date 2018-12-03T00:00:00.000Z  
Date 2018-11-30T00:00:00.000Z

1 个答案:

答案 0 :(得分:0)

您的循环中有

if (fourDaysDow !== 0 || fourDaysDow !== 6 || !bankHolidays.includes(fourDaysStr))

这些应该是&&运算符。 如果不是星期日,不是星期六,也不是节假日 (星期六不是星期天,因此OR表达式在您的代码中为true)

它来自这个布尔代数定理-当您​​发现自己反转表达式的布尔成分时,了解这一点至关重要。

NOT (A AND B) == NOT A OR NOT B
NOT (A OR B) == NOT A AND NOT B