'How can I make my API date field to be 3 business days from today's date taking weekends (Sat and Sun) into account using JS?

I am using javascript for to communicate with platform's api. Just have a quick question!

There is a date picker which you can click and pick any date. My task here is to build a JS code that can communicate with the Date variable and won't let it select a date more than 3 business days for e.g: today is 22/04 and the max one can select is 25/04. I have already built this code which you can see below.

My questions is how I can take weekends into account in this code? Like if Sat/Sun falls within then they won't be counted. Only business days will be counted!

Any assistance will be highly appreciated!

Code snippet:


const DateVar = "DATE"; /* name of the date variable in Checkbox to apply validation to */

events[`change:${DateVar}`] = async () => {


    const days = 3; /* how many days from today the user is able to select dates*/

    const today = new Date();

    let validationPeriodStart = new Date(today.setDate(today.getDate() + days));

    /* VALIDATION FUNCTION */

    const result = form.ShowCustomValidation(DateVar, [(value) => {

        /* transform the selected date into JS Date object */
        const selectedDate = new Date(value);

        /* validate if the selected date is before the period where user can select dates (today + 3 weeks and onward) */

        const RESULT = value && selectedDate < validationPeriodStart ?
            `Error: Please make sure your date is after the ${validationPeriodStart.toLocaleDateString('en-SG')}` : undefined;

        return RESULT;

    }
    ]);

    /* throw a pop-up error in the top right corner - remove if not required */
    if (result) { form.SetError(result) };

};

addEvents(events);```


Solution 1:[1]

A full-fledged solution would take into account holidays of fixed and variable dates and thus be highly dependent on precise geolocation data. A less picky solution would harvest holiday databases for relevant locales compiling local calendar data structures comprising a holiday flag.

For the basic step of excluding Sat/sun, use the Date.getDay() method.

The following sample code (replace you code line let validationPeriodStart = new Date(today.setDate(today.getDate() + days));`` with it) defines a current date and advances it in steps of 1 day, each turn testing for Saturday/Sunday, until the datetime horizon is exhausted. Computations are performed in the domain of the epoch defined by milliseconds since 1970/01/01.

let d_current = new Date()
  , n_horizonDistance = days
  , validationPeriodStart 
  ;
while (n_horizonDistance > 0) {
    let n_dow = d_current.getDay()
      ;
    if ((n_dow !== 0) && (n_dow !== 6)) {
        n_horizonDistance--;
    }
    d_current = new Date(d_current.getTime() + 1000 * 3600 * 24); // + 1 day
}

The method caters for month and year spillovers (including leap years) but not for DST. It can easily be extended, eg. checking for holidays. Consult MDN Docs for more info on the JS Date object and its features.

More flexibility and cleaner code and is achieved by precomputing the cutoff dates for a certain period of time and store the data in the server-side db.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 collapsar