Created
December 26, 2017 06:16
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 Hi!, I also had problems in the differences, I solved it based on the date in UTC, change the functions for example from getDay
to getUTCDay
, because the day 2022-10-30
is Sunday, and getDay
takes me as 6, it should be 0
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)
This would be great if you could have an option that deals with holidays as well...just saying...
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
Great code, there is just one issue when dates are in different daylight saving times. See result with these dates (30. is where daylight saving time changes in our country):
5 Days would be expected result. But function returns 4. I managed to fix this issue by adding:
Just after time normalization. Hope it helps you or others finding this function ;-)