calcJSLib.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. function isValidDate(d) {
  2. if ( Object.prototype.toString.call(d) !== "[object Date]" )
  3. return false;
  4. return !isNaN(d.getTime());
  5. }
  6. // Logic inspired from http://snipplr.com/view/4086/
  7. function calcBusinessDaysDiff(dDate1, dDate2) { // input given as Date objects
  8. var iWeeks, iDateDiff, iAdjust = 0;
  9. if (dDate2 < dDate1) return -1; // error code if dates transposed
  10. var iWeekday1 = dDate1.getDay(); // day of week
  11. var iWeekday2 = dDate2.getDay();
  12. iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
  13. iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
  14. if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
  15. iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
  16. iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
  17. // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
  18. iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
  19. if (iWeekday1 <= iWeekday2) {
  20. iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
  21. } else {
  22. iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
  23. }
  24. iDateDiff -= iAdjust // take into account both days on weekend
  25. return (iDateDiff);
  26. }
  27. // Logic inspired from http://lists.evolt.org/pipermail/javascript/2002-September/003983.html
  28. function addBusinessDays(dDate,days) { // dDate = starting date, days = no. working days to add.
  29. var temp_date = new Date();
  30. var i = 0;
  31. var iDaysToAdd = 0;
  32. var iPlusMinus = days >= 0 ? 1 : -1
  33. while (i < Math.abs(Math.floor(days))){
  34. temp_date = new Date(dDate.getTime() + (iPlusMinus * iDaysToAdd*24*60*60*1000));
  35. //0 = Sunday, 6 = Saturday, if the date not equals a weekend day then increase by 1
  36. if ((temp_date.getDay() != 0) && (temp_date.getDay() != 6)){
  37. i+=1;
  38. }
  39. if ((iPlusMinus==1 && temp_date.getDay() == 5) || (iPlusMinus==-1 && temp_date.getDay() == 1))
  40. // for +, on Friday, add 3 days to skip to next Monday; for -, on Monday, minus 3 days to skip to last Friday
  41. iDaysToAdd += 3
  42. else
  43. iDaysToAdd += 1;
  44. }
  45. return new Date(dDate.getTime() + (iPlusMinus * iDaysToAdd*24*60*60*1000));
  46. }