-
-
Save jcbagtas/8c622d294fe8ad12bb4af59f8543ce71 to your computer and use it in GitHub Desktop.
/**** | |
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; | |
}; |
Should return 1 for endDate = startDate ?
Should return 1 for endDate = startDate ?
A dusty 3 year-old snippet is still relevant I see. lol
You are right. There should be a return, not just null. But I guess I had a reason why it's null, I can't quite remember now. lol
Lekker ! thanks man ! 👍
No prob.
Sweet! Just what I was looking for. Thanks!
Sweet! Just what I was looking for. Thanks!
glad this still helps. cheers!
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?
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.
Lekker ! thanks man ! 👍