Change the week period on differenceInBusinessDays? #4066
Replies: 1 comment
|
There's no option for this, checked the current source of export function differenceInBusinessDays(
laterDate: DateArg<Date> & {},
earlierDate: DateArg<Date> & {},
options?: DifferenceInBusinessDaysOptions | undefined,
): number {
...
let result = weeks * 5;
...
while (!isSameDay(laterDate_, movingDate)) {
result += isWeekend(movingDate, options) ? 0 : sign;
movingDate = addDays(movingDate, sign);
}
...
}The export function isWeekend(date, options) {
const day = toDate(date, options?.in).getDay();
return day === 0 || day === 6;
}No configurability there either, Saturday/Sunday is baked in. This isn't just undocumented, there's genuinely no plumbing for a custom weekend definition anywhere in this function's option surface. Given date-fns' general philosophy of small composable functions rather than parameterizing every variant into one function, the practical way to get a 6/1 week is to build it from import { eachDayOfInterval } from "date-fns";
function differenceInSixDayWorkWeek(laterDate: Date, earlierDate: Date) {
const [start, end] = laterDate < earlierDate
? [laterDate, earlierDate]
: [earlierDate, laterDate];
const sign = laterDate < earlierDate ? -1 : 1;
const count = eachDayOfInterval({ start, end })
.filter(d => d.getDay() !== 0) // only Sunday is off
.length - 1; // exclude the start day itself, matching differenceInBusinessDays' semantics
return count * sign;
}Adjust the |
Uh oh!
There was an error while loading. Please reload this page.
I am trying to make use of the differenceInBusinessDays and so far the function has been superb, but im wondering if there is a way to change the period of a business week i.e. the default is currently 5 - 2, 5 working days 2 weekend days, is there a way to change the options on the function so the period is 6 - 1, 6 working days 1 weekend day?
const working_days = differenceInBusinessDays(current_date, previous_month, options: { business_days: 6 });All reactions