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

后端 未结 3 1455
日久生厌
日久生厌 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:10

    If you only want to add 7 days and exclude holidays and weekends (assuming Saturday and Sunday), then you can just step from the start to the end and test each day as you go:

    var ukHolidays = ['2017-05-12','2017-05-29','2017-08-28','2017-12-25','2017-12-26'];
    
    // Return date string in format YYYY-MM-DD
    function getISODate(date){
      function z(n) {return (n<10?'0':'')+n}
      return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate());  
    }
    
    // Modifies date by adding 7 days, excluding sat, sun and UK holidays
    function add7WorkingDays(date) {
      for (var i=7; i; i--) {
        // Add a day
        date.setDate(date.getDate() + 1);
    
        // If a weekend or holiday, keep adding until not
        while(!(date.getDay()%6) || ukHolidays.indexOf(getISODate(date)) != -1) {
          date.setDate(date.getDate() + 1);
        }
      }
      return date;
    }
    
    // Add 7 working days to today
    var d = new Date();
    console.log('Add 7 working days to ' + d.toString() + 
                '\nResult: ' + add7WorkingDays(d).toString());

提交回复
热议问题