Skip to content

Instantly share code, notes, and snippets.

@mazfreelance
Created December 26, 2017 06:16
Show Gist options
  • Save mazfreelance/0660c50a65ab56c5eb400447275a8f32 to your computer and use it in GitHub Desktop.
Save mazfreelance/0660c50a65ab56c5eb400447275a8f32 to your computer and use it in GitHub Desktop.
Javascript : Calculate business days between two (2) dates, business days (Monday to Friday)
function calculateBusinessDays(startDate, endDate){
// Validate input
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days = days - 1;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days = days - 1;
}
return days;
}
@sadovsf
Copy link

sadovsf commented Aug 3, 2022

Thank you, i would have to test it. Solution I provided is working as expected (I did autotests to validate that and using it in app iam building which relies on it heavily)

@krestel
Copy link

krestel commented Aug 22, 2022

This would be great if you could have an option that deals with holidays as well...just saying...

@rushikpatel08
Copy link

there is one issue with this code if you enter following date
start date=april 10 2023
end date=april 17 2023
it returning 5 instead of 6
every monday is not counted if you can check

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment