计算两个日期之间的工作日

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算两个日期之间的工作日相关的知识,希望对你有一定的参考价值。

This routine is loosely based on elightbo's "Calculate Business Days" snippet in ASP, with some process & logic modifications (most notably accounting for situations when both dates fall on a weekend) and a translation to javascript.
  1. function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
  2.  
  3. var iWeeks, iDateDiff, iAdjust = 0;
  4.  
  5. if (dDate2 < dDate1) return -1; // error code if dates transposed
  6.  
  7. var iWeekday1 = dDate1.getDay(); // day of week
  8. var iWeekday2 = dDate2.getDay();
  9.  
  10. iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
  11. iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
  12.  
  13. if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
  14.  
  15. iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
  16. iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
  17.  
  18. // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
  19. iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
  20.  
  21. if (iWeekday1 <= iWeekday2) {
  22. iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
  23. } else {
  24. iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
  25. }
  26.  
  27. iDateDiff -= iAdjust // take into account both days on weekend
  28.  
  29. return (iDateDiff + 1); // add 1 because dates are inclusive
  30.  
  31. }

以上是关于计算两个日期之间的工作日的主要内容,如果未能解决你的问题,请参考以下文章

Excel中计算两个日期之间的天数,扣除周六周日

如何计算两个日期之间的营业时间(R语言)?

计算两个日期之间的工作日

计算两个日期之间的工作日

(013)每日SQL学习:确定两个日期之间的工作日天数和计算一年周内各日期次数

Pandas - 如何根据自定义日历计算两个日期之间的天数[关闭]