1. Computing & Technology

Day Difference and Business Day Difference

Adding to the Date Object

Determining the number of days between two dates id not too difficult if you remember how date objects work. Calculating the number of business dayts (excluding weekends from the count) is somewhat more complicated. Excluding holidays as well is just about impossible unless you restrict your date range to a short period at a specific location and deduct for all those dates that are within the range between the two dates.

I'm not going to worry about holidays here as the processing for that is somewhat different from what we need to get the number of days between two dates. We are just going to look at adding two extra methods that will give us the number of days between two dates with the second of them not counting weekends.

Since we are going to add these methods to our dates and the methods need two dates to calculate the difference we'll need to pass the second date into the methods as a parameter. To be flexible since the methods are actually going to be attached to both dates we will not care which of the two dates we call the method from and which we pass as a parameter. We therefore will make no assumptions as to which is the greater date. For the simpler days difference function we can simply ignore any minus sign on our answer. For the one ignoring weekends we'll also have to check on the days of the week and will need to know which is the earlier and which the later date for that comparison so things get a little more complicated. Anyway I've done all the hard work for you because here are the two methods ready for you to add them to your page.

Date.prototype.dayDiff = function(d2) {
var d= Math.abs(this-d2);
return Math.floor(d/(24*60*60*1000));}
 
Date.prototype.busDayDiff = function(d2) {
var d = this.dayDiff(d2); var t= d%7;
if (this < d2) {w1= this.getDay(); w2= d2.getDay();}
else {w2= this.getDay(); w1= d2.getDay();}
if (w1 > w2) t-=2;if ((w1 == 0 && w2 == 6) || w1 == 6) t--;
return Math.abs((Math.floor(d/7)*5)+t);}

Just to make things interesting for the code demonstrating how to call the method to get the number of business days between two dates lets work out how many business days there have been since 19th September 2004. Here's the code to do that.

var d1 = new Date();
var d2 = new Date(2004,8,19);
alert(d1.busDayDiff(d2));

Of course you can set the two dates using any of the usual ways and you can call the method from anywhere not just from in an alert. In fact I can use an innerHTML reference to tell you that the answer to the number of days (excluding weekends) since 19th September 2004 is .

©2012 About.com. All rights reserved.

A part of The New York Times Company.