Wednesday 3 September 2014

Java program to calculate the number of business days between two dates.

This is a Java program to calculate the  number of business days between two dates..
This program will exclude only Saturdays & Sundays and not the public holidays.

public long getNumberOfBusinessDays(Date start, Date end) 
    {
        if (start == null || end == null)  
            return 0;

        long daysWithoutSunday = 0;
        int w1 = 0;
        int w2 = 0;
        
        Calendar c1 = GregorianCalendar.getInstance();
        c1.setTime(start);
        w1 = c1.get(Calendar.DAY_OF_WEEK);
        c1.add(Calendar.DAY_OF_WEEK, -w1 + 1);

        Calendar c2 = GregorianCalendar.getInstance();
        c2.setTime(end);
        w2 = c2.get(Calendar.DAY_OF_WEEK);
        c2.add(Calendar.DAY_OF_WEEK, -w2 + 1);

        //end Saturday to start Saturday 
        long days = (c2.getTimeInMillis() - c1.getTimeInMillis())/(1000*60*60*24);
        
        daysWithoutSunday = days-(days*2/7);

        if (w1 == Calendar.SUNDAY) 
            w1 = Calendar.MONDAY;
        
        if (w2 == Calendar.SUNDAY) 
            w2 = Calendar.MONDAY;
       
        return daysWithoutSunday-w1+w2;
    }
 

No comments: