Search code examples
javascriptangularjsdatemomentjsangular-moment

Exclude weekend dates from working days in JavaScript


So I am kinda stuck in figuring out a certain aspect. What I want to do is the following:

Let's say I just have a simple date display, which will show a date such as October 10th, 2017 to an end user. And then there is an option to subtract a certain number of days from said date (an offset of 1, 2, 3, whatever offset is chosen).

What I am looking to do is completely exclude weekend dates from the count - so if today is Monday, October 9th, and an offset of 1 is selected, it goes to Friday the 6th; if an offset of 2 is chosen, it goes to Thursday the 5th; an offset of 3 goes to Wednesday the 4th...

If today was Wednesday, October 11th, an offset of 2 would take you to Monday the 9th, an offset of 4 would go to Thursday the 5th, and so on (completely disregards / skips weekend dates when counting / subtracting which day to land on).

I have so far been able to only find answers for the functionality to calculate the number of working days excluding weekends, and things of that nature (which I already have, using the momentjs-business npm module, but is not exactly what I need).

I did not post code because this is part of a much larger code base, and I feel posting snippets would only add to the confusion, since I believe the question is relatively simply and straightforward; I do not want to over complicate.

All I would like is to not include weekends at all when setting an offset from whichever date is displayed to the user (the date which is displayed to the user is from a database).

I hope this all made sense, and if more info is needed, please let me know. Thanks in advance for anyone that can point me in the right direction!


Solution

  • This will achieve what you want I think. Please note this is terribly inefficient. If your offset is very large it generates a new date every iteration of the loop. With some tinkering it could be optimized

    let startDate = new Date('10/10/2017');
    let endDate = "", offset = 2;
    while(offset > 0){
        endDate = new Date(startDate.setDate(startDate.getDate() - 1));
        if(endDate.getDay() !== 0 && endDate.getDay() !== 6){
           offset--;
        }
    }
    

    Here is a working Fiddle