3

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;
}
user11809641
  • 815
  • 1
  • 11
  • 22
Leggeth
  • 33
  • 4
  • 2
    Some tips for you: Use the English name of variables. Use Polish (or other languages) is a bad practice. Use `const` and `let` instead of `var` syntax. More info about it here: https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/ And also you can use something like this: `const work = \`${day}.${month}.${year}\``; – Kordrad Jun 30 '21 at 09:24
  • 2
    @Kordrad _"Use Polish (or other languages) is a bad practice"_ - why? – evolutionxbox Jun 30 '21 at 09:28
  • 2
    @evolutionxbox because if other developers will look at your code, they understand what the name of variables means. Sure, if you making a project for only polish clients no one will be angry for writing in Polish. But for better clear code, just use English names. – Kordrad Jun 30 '21 at 09:36

1 Answers1

2

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())
Kordrad
  • 1,154
  • 7
  • 18
Martin Meli
  • 452
  • 5
  • 18
  • I still got one question. What if the code is executed on Thursday after 10am it will add two days so the final date will be on Saturday?If yes , how to prevent it ? – Leggeth Jul 01 '21 at 08:22
  • add a specific condition, `if (dayOfWeek == 4)`, don't add two days – Martin Meli Jul 01 '21 at 08:23