0

I am working on program that displays the number of workdays in the month passed up until today. For example, today is the 9th of September, so the program should display the number 7, as there has been one weekend up until that day. If today was the 20th of September, the program should display the number 14, as there has been 3 weekends up until that date. (With weekends I mean only Saturday and Sunday).

This is the code I currently have:

date = new Date();
let dayD = date.getDate();
let newDay = dayD - 2; // Temporarily done manually as I don't have the code to automatically do it yet
console.log(newDay);

I have seen several similar questions but none that was similar enough or that actually helped me. So, how could I count the days in the month passed until today, but excluding the weekends (Only workdays)?

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Pauliecode
  • 107
  • 2
  • 9
  • 1
    When you say 'workdays' shouldn't you consider Holidays? – Yevhen Horbunkov Sep 09 '21 at 08:52
  • take a look at this: https://stackoverflow.com/questions/37069186/calculate-working-days-between-two-dates-in-javascript-excepts-holidays – nlarche Sep 09 '21 at 08:53
  • 2
    If I had to do this without a date library, I would probably just [build an array of dates between the two points](https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates), then [filter it by not-weekends](https://stackoverflow.com/questions/3551795/how-to-determine-if-date-is-weekend-in-javascript) and grab the length. – DBS Sep 09 '21 at 08:54
  • @YevgenGorbunkov The assignment specifies to ignore holidays :) – Pauliecode Sep 09 '21 at 08:56

1 Answers1

1

You may build up an array of Dates and check for desired day (not to be Saturday or Sunday):

const workdaysCount = () => 
  [...new Array(new Date().getDate())]
    .reduce((acc, _, monthDay) => {
      const date = new Date()
      date.setDate(1+monthDay)    
      ![0, 6].includes(date.getDay()) && acc++
      return acc      
    }, 0)
    
console.log(workdaysCount())    
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42