JavaScript to Calculate Business Working Days between Two Dates

One of the customer gives us a requirement to calculate the business working days between start and end date, so by calculating the business day they can set the limit between start and end date that how much day it will take to complete work including business days only.

Follow the below steps: –

Step 1: -Create a web Resource select type JavaScript

Settings->Customization->Customize the System->web resource

clip_image002

Click on setting customizations then customization open then select customize your system then Default solution opens then click on web resource and create as shown below

clip_image003

Step 2: – Paste the following script in web resource

1 function workingDaysBetweenDates() 2 { 3 var startDate = Xrm.Page.getAttribute("new_startdate").getValue(); 4 var endDate = Xrm.Page.getAttribute("new_enddate").getValue() 5 // Validate input 6 if (endDate < startDate) 7 return 'Invalid !'; 8 9 // Calculate days between dates 10 var millisecondsPerDay = 86400 * 1000; // Day in milliseconds 11 startDate.setHours(0, 0, 0, 1); // Start just after midnight 12 endDate.setHours(23, 59, 59, 999); // End just before midnight 13 var diff = endDate - startDate; // Milliseconds between datetime objects 14 var days = Math.ceil(diff / millisecondsPerDay); 15 16 // Subtract two weekend days for every week in between 17 var weeks = Math.floor(days / 7); 18 var days = days - (weeks * 2); 19 20 // Handle special cases 21 var startDay = startDate.getDay(); 22 var endDay = endDate.getDay(); 23 24 // Remove weekend not previously removed. 25 if (startDay - endDay > 1) 26 days = days - 2; 27 28 29 // Remove start day if span starts on Sunday but ends before Saturday 30 if (startDay == 0 && endDay != 6) 31 days = days - 1; 32 33 // Remove end day if span ends on Saturday but starts after Sunday 34 if (endDay == 6 && startDay != 0) 35 days = days - 1; 36 Xrm.Page.getAttribute("new_day").setValue(days); 37 } 38

 

Step 3: – Save and Publish Web Resource

clip_image005

Step 4: -Add the Days attribute on form under start and end date to store result in it

clip_image006                     clip_image007

Step 5: -Click to form Property and set event hander onChange of End date and put function name there

clip_image009

Then form property open then add web resource

clip_image011

Select web resource and select event as onChange of end date and add event handler and provide function name as shown below

clip_image013                       clip_image015

Step 6: -Save and publish the form

Step 7: -Result

clip_image016

Leave a comment