7

So basicly I am trying to use addBusinessDays(new Date(), 3) which sets a startdate without taking weekends into account. However I need to make use of a list of dates ( holidays ) into this aswell. I can't find any documentation on how to add those holidays to the addBusinessDays.

I am using date-fns v2+

Example code:

import { addBusinessDays } from 'date-fns';

const holidays = [
  '2019-12-20'
]

console.log(addBusinessDays(new Date(), 3)) // should include holidays => 2019-12-24
Joelgullander
  • 1,624
  • 2
  • 20
  • 46
  • Do no use the built–in parser, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Since you're using date-fns, use [its parser](https://date-fns.org/v2.8.1/docs/parseISO). – RobG Dec 18 '19 at 12:57

1 Answers1

-3

You could perhaps do something like this?

const newHolidays = holidays.map(holiday => {
  return addBusinessDays(new Date(holiday), 3);
});

console.log(newHolidays);

newHolidays - This is a new array (leaving the original intact) containing each of the dates + 3 days

Read about .map here

.map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

You may want to also 'parse' the dates using date-fns as mentioned in the comments. You could do this like so:

function parseDates(dates) {
  return dates.map(date => {
    return parse(date, "yyyy-MM-dd", new Date());
  });
}

const parsedHolidays = parseDates(holidays);

Then you would want to change 'newHolidays' to similar to this:

const newHolidays = parsedHolidays.map(holiday => {
  return addBusinessDays(new Date(holiday), 3);
});

Or, you could move the parse function into the holidays.map if you'd prefer to parsed them one by one just before using addBusinessDays

Inch High
  • 835
  • 5
  • 17