Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript how to exclude saturdays?

I’ve found this code online to return the next working day and exclude weekends.

function nextWorkDay() {
    const date = new Date();
  do {
    date.setDate(date.getDate() + 1);
  } while (!(date.getDay() % 6));
  return date;
}

However, the % 6 part in my understanding excludes Saturdays and Sundays.
How can I modify it to only exclude Saturdays?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

getDay returns a value between 0 and 6, inclusive. 0 is Sunday.

So, date.getDay() % 6 will result in 0 if getDay returns either 0 or 6.

Don’t use modulo – use === to exclude exactly one day, not both zero and another day.

} while (date.getDay() === 6);

You also don’t need a loop anymore – a single condition will be clearer.

function nextWorkDay() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    if (date.getDay() === 6) date.setDate(date.getDate() + 1);
    return date;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading