26th January 2011

Calculate business days between 2 dates

I have recently been working on a tool to display human resource allocation data in a gantt style chart indicating where a resource has been allocated and for how long as well as taking in to account other categories of allocation such as holidays. Whilst the tool worked great in to a small challenge correctly calculating the number of business/working days within a period of allocation.

The end result is the below Javascript. This Javascript takes 2 dates and returns the number of business days between the 2 dates.

Enjoy.

    var DateUtils = {

        daysBetween: function (start, end) {
		if (!start || !end) { return 0; }
		start = Date.parse(start); end = Date.parse(end);
		var count = 0, date = start.clone();
		while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
		return count;
        },
	businessdays: function(dDate1, dDate2) {
        	var d = DateUtils.daysBetween(dDate1,dDate2);
        	var t= d%7;
  
		if (dDate1 < dDate2) {
			w1 = dDate1.getDay(); 
			w2 = dDate2.getDay();
		}
		else {
			w2 = dDate1.getDay(); 
			w1 = dDate2.getDay();
		}
 
		if (w1 > w2) { t -= 2; }
		if (w1 == 0 && w2 == 6) { t--; }
		return Math.abs((Math.floor(d / 7) * 5) + t);
	}
    };
    
    //example invocation
    var date1 = new Date(2011,0,1);
    var date2 = new Date(2011,1,5);
    
    DateUtils.businessdays(date1,date2);

Share |