SHARE
TWEET

Untitled

a guest Jun 18th, 2019 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var moment = require('moment');
  2.  
  3. function calculateBusinessDays(firstDate, secondDate){
  4.   //Initiallize variables
  5.   var day1 = moment(firstDate);
  6.   var day2 = moment(secondDate);
  7.   var adjust = 0;
  8.  
  9.   if((day1.dayOfYear() === day2.dayOfYear()) && (day1.year() === day2.year())){
  10.     return 0;
  11.   }
  12.  
  13.   //Check if second date is before first date to switch
  14.   if(day2.isBefore(day1)){
  15.     day2 = moment(firstDate);
  16.     day1 = moment(secondDate);
  17.   }
  18.  
  19.   //Check if first date starts on weekends
  20.   if(day1.day() === 6) { //Saturday
  21.     //Move date to next week monday
  22.     day1.day(8);
  23.   } else if(day1.day() === 0) { //Sunday
  24.     //Move date to current week monday
  25.     day1.day(1);
  26.   }
  27.  
  28.   //Check if second date starts on weekends
  29.   if(day2.day() === 6) { //Saturday
  30.     //Move date to current week friday
  31.     day2.day(5);
  32.   } else if(day2.day() === 0) { //Sunday
  33.     //Move date to previous week friday
  34.     day2.day(-2);
  35.   }
  36.  
  37.   var day1Week = day1.week();
  38.   var day2Week = day2.week();
  39.  
  40.   //Check if two dates are in different week of the year
  41.   if(day1Week !== day2Week){
  42.     //Check if second date's year is different from first date's year
  43.     if (day2Week < day1Week){
  44.       day2Week += day1Week;
  45.     }
  46.     //Calculate adjust value to be substracted from difference between two dates
  47.     adjust = -2 * (day2Week - day1Week);
  48.   }
  49.  
  50.   return day2.diff(day1, 'days') + adjust;
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top