Last active
November 11, 2023 18:46
-
-
Save jcbagtas/8c622d294fe8ad12bb4af59f8543ce71 to your computer and use it in GitHub Desktop.
Calculate Working Days between two dates. Javascript equivalent of Microsoft Excel's NETWORKDAYS() function.
This file contains 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
/**** | |
Javascript equivalent of Microsoft Excel's NETWORKDAYS() function. | |
Calculate Working Days between two dates. | |
Optimized for performance. accepts String '12/18/1990' and new Date('12/18/1990') Object. | |
usage: | |
networkdays('12/18/1990','12/18/2016'); | |
networkdays(new Date(),'12/18/2016'); | |
http://bgtsworks.blogspot.com/ | |
*****/ | |
networkdays = function(startDate,endDate){ | |
var startDate = typeof startDate=='object' ? startDate: new Date(startDate); | |
var endDate = typeof endDate=='object' ? endDate: new Date(endDate); | |
if (endDate > startDate){ | |
var days = Math.ceil((endDate.setHours(23,59,59,999) - startDate.setHours(0,0,0,1)) / (86400 * 1000)); | |
var weeks = Math.floor(Math.ceil((endDate.setHours(23,59,59,999) - startDate.setHours(0,0,0,1)) / (86400 * 1000)) / 7); | |
days = days - (weeks * 2); | |
days = startDate.getDay() - endDate.getDay() > 1 ? days - 2 : days; | |
days = startDate.getDay() == 0 && endDate.getDay() != 6 ? days - 1 : days; | |
days = endDate.getDay() == 6 && startDate.getDay() != 0 ? days - 1 : days; | |
return days; | |
} | |
return null; | |
}; |
what does (86400 * 1000) represent?
when calculating days, Math.ceil returns the wrong number of days when the input is as follows:
startDate - Mon Nov 01 2021 00:00:00 GMT-0700 (Pacific Daylight Time)
endDate - Tue Nov 30 2021 23:59:59 GMT-0800 (Pacific Standard Time)
days - 30.041666643518518Would Math.round be a better option? Or is the above input incorrect?
You may be right, rounding off days can be useful most of the times.
what does (86400 * 1000) represent?
Milliseconds per day.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
when calculating days, Math.ceil returns the wrong number of days when the input is as follows:
startDate - Mon Nov 01 2021 00:00:00 GMT-0700 (Pacific Daylight Time)
endDate - Tue Nov 30 2021 23:59:59 GMT-0800 (Pacific Standard Time)
days - 30.041666643518518
Would Math.round be a better option? Or is the above input incorrect?