This is a Java Program for calculating business days considering 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;
long actualNumberOfBusinessDays = 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;
/*
* Check if the there are dates which are falling in public holidays?
* Currently handling only Christmas & New Year days.
*/
long numberOfBusinessDaysWithoutSundayAndSaturday = daysWithoutSunday - w1 + w2;
actualNumberOfBusinessDays = numberOfBusinessDaysWithoutSundayAndSaturday;
while (numberOfBusinessDaysWithoutSundayAndSaturday > 0 && start.before(end))
{
if (isPublicHoliday(start))
actualNumberOfBusinessDays -= 1;
start = addDay(start);
numberOfBusinessDaysWithoutSundayAndSaturday -= 1;
}
return actualNumberOfBusinessDays;
}
public static boolean isPublicHoliday(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w1 = cal.get(Calendar.DAY_OF_WEEK);
// check if New Year's Day & not falls on a Saturday or Sunday because weekends are already taken care
if (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) == 1 && w1 != Calendar.SUNDAY && w1 != Calendar.SATURDAY)
return true;
// check if Christmas & not falls on a Saturday or Sunday because weekends are already taken care
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER && cal.get(Calendar.DAY_OF_MONTH) == 25 && w1 != Calendar.SUNDAY && w1 != Calendar.SATURDAY)
return true;
return false;
}
private static Date addDay(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
No comments:
Post a Comment