Set date to 7 working days from today (excluding weekends and public holidays)

后端 未结 3 1418
日久生厌
日久生厌 2021-01-24 08:30

I\'m trying to set a date to 7 working days from today\'s date (excluding weekends and UK public holidays).

  1. I start by setting the default date to today\'s date (t
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 09:32

    Here is an example of what @andi is talking about. I made it as a calculator object.

    var calculator = {
        workDaysAdded: 0,
        ukHolidays: ['2017-05-12','2017-05-29','2017-08-28','2017-12-25','2017-12-26'],
        startDate: null,
        curDate: null,
    
        addWorkDay: function() {
            this.curDate.setDate(this.curDate.getDate() + 1);
            if(this.ukHolidays.indexOf(this.formatDate(this.curDate)) === -1 && this.curDate.getDay() !== 0 && this.curDate.getDay() !== 6) {
                this.workDaysAdded++;
            }
        },
    
        formatDate: function(date) {
            var day = date.getDate(),
                month = date.getMonth() + 1;
    
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return date.getFullYear() + '-' + month + '-' + day;
        },
    
        getNewWorkDay: function(daysToAdd) {
            this.startDate = new Date();
            this.curDate = new Date();
            this.workDaysAdded = 0;
            
            while(this.workDaysAdded < daysToAdd) {
                this.addWorkDay();
            }
            return this.curDate;
        }
    }
    
    var newWorkDay7 = calculator.getNewWorkDay(7);
    var newWorkDay9 = calculator.getNewWorkDay(9);
    var newWorkDay14 = calculator.getNewWorkDay(14);
    console.log(newWorkDay7);
    console.log(newWorkDay9);
    console.log(newWorkDay14);

提交回复
热议问题