Javascript to calculate Work days

Hello,
I am not good with Javascript so any help is welcome.

I’m trying to calculate what is the next workday after X days by using the below code, but for some reason it is not returning anything.
The code is returning the good value on JSFiddle tho.

image

const holidays = {p3};
const startDate = new Date(p1);
const numDays = p2;
const futureDate = addWorkingDays(startDate, numDays);

function isHoliday(date) {
  const dateString = date.toISOString().slice(0, 10);
  return dateString in holidays;
}

function addWorkingDays(startDate, numDays) {
  let currentDate = new Date(startDate.getTime());
  let daysAdded = 0;

  while (daysAdded < numDays) {
    currentDate.setDate(currentDate.getDate() + 1);

    // Check if the current day is a weekend or holiday
    if (currentDate.getDay() === 0 || currentDate.getDay() === 6 || isHoliday(currentDate)) {
      continue; // Skip weekends and holidays
    }

    // If it's a working day, increment the counter
    daysAdded++;
  }

  return currentDate;
}
const holidays = {p3};

I think this looks weird. Are you trying to establish an array here?

When I’ve used javascript in Glide, normally I need to convert variables (p1, p2, p3) in types that I need. For example: If you pass p3 as joined_holidays like ‘1,2,3,4,5’, you need to do…

const holidays = p3.split(',').map(Number);

You also can force convert p2 to int with parseInt…

const numDays = parseInt(p2);

And in date case, you need to pass p1 with a date format like “yyyy-MM-dd” and try convert to string before convert to date…

const startDate = new Date(String(p1)); // 2023-07-13

Try this and comment.

1 Like

You also don’t have any code to return a value. It may be calculating futureDate, but it’s just sitting there. You need to add the following to actually return that value.

return futureDate;

Hola @Thais_Fontes

Months ago we had a similar case and this was my solution. Although it can be done via JS, I preferred to use a no code one (I read it twice and I don’t even believe it myself :rofl:)

Feliz día!

You are right!
I had tried this before but I believe I was using the wrong date format for the workday() formula to work.

Thanks!!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.