Search code examples
javascriptgetdate

Add days but skip weekends


I have a small problem. I have a working code for adding days depending on the current time (if it is before 10am it adds 1 day if it is after 10am it adds 2 days for the date). So here is my question: How can I edit the code so it will skip the weekends in the calculations? For example, if I execute it before 10am on Friday it should show me the Monday date, not Saturday or Sunday.

function onGetMultiValue() {
    var dzis    = new Date();
    var Godzina = new Date().getHours();
    var teraz   = dzis.getDate();
    
    if (Godzina < 10) {
        dzis.setDate(dzis.getDate() + 1);
    } else {
        dzis.setDate(dzis.getDate() + 2);
    }
    
    var day   = dzis.getDate();
    var month = dzis.getMonth() + 1;
    var year  = dzis.getFullYear();
    var praca = day+"."+month+"."+year;

    return praca;
}

Solution

  • You can use getDay() to check which day of the week it is.

    function onGetMultiValue() {
      const today     = new Date();
      const hour      = new Date().getHours();
      const dayOfWeek = today.getDay();
       
      if (dayOfWeek == 5) {
        // if it's Friday add 3 days to the date
        today.setDate(today.getDate() + 3);
      }
    
      today.setDate(today.getDate() + hour < 10 ? 1 : 2)  
    
      const day   = today.getDate();
      const month = today.getMonth() + 1;
      const year  = today.getFullYear();
    
      return `${day}.${month}.${year}`;
    }
    
    console.log(onGetMultiValue())