Saturday, June 16, 2012

The objectlabkit Comes to Calculate Working Days

There was this requirement for my project to calculate delivery date estimation. The delivery date is estimated to be 40 working days, in this case I have to exclude Saturday-Sunday and any holidays.

Fortunately there is a library from sourceforge named objectlabkit which can be found here. The latest version was 1.2.0 and I would like to share here how it helped me out:

Create a set of holidays. This is a list of holidays to be excluded from working days.
Calendar firstHoliday = Calendar.getInstance();
firstHoliday.set(Calendar.DAY_OF_MONTH, 18);
firstHoliday.set(Calendar.MONTH, Calendar.JANUARY);
...
Set<calendar> holidays = new HashSet<calendar>();
holidays.add(firstHoliday);
holidays.add(secondHoliday);
Create start and end calendar as a boundary.

In some condition, the holidays are supplied by a service which we can not control and the list could contain holidays from 1990 to 2020 while we are only interested in holidays in 2012. That is why we need the start and end calendar as a boundary.
Calendar earlyBoundary = Calendar.getInstance();
earlyBoundary.set(Calendar.DAY_OF_MONTH, 1);
earlyBoundary.set(Calendar.MONTH, Calendar.JANUARY);

Calendar lateBoundary = Calendar.getInstance();
lateBoundary.set(Calendar.DAY_OF_MONTH, 31);
lateBoundary.set(Calendar.MONTH, Calendar.DECEMBER);
Create an object named HolidayCalendar and register it to CalendarKitCalculatorsFactory.

After creating the boundaries, we have to register the holiday list and the boundaries to an object of type CalendarKitCalculatorsFactory. We need to supply an id when registering to the object so that we can request a DateCalculator object from it later.
HolidayCalendar<calendar> holidayCalendar = new DefaultHolidayCalendar<calendar>(holidays, earlyBoundary, lateBoundary);
CalendarKitCalculatorsFactory.getDefaultInstance().registerHolidays("ID", holidayCalendar);
Get DateCalculator object from CalendarKitCalculatorsFactory by supplying the previously registered id.

The only thing to note here is the HolidayHandlerType constant. In this example I use FORWARD because when the estimated delivery date falls on either Saturday-Sunday or holidays I want the estimated delivery date to be the next available working day.
DateCalculator<calendar> dateCalculator = CalendarKitCalculatorsFactory.getDefaultInstance().getDateCalculator("ID", HolidayHandlerType.FORWARD);
Set the start date.

We need to set start date when the calculation must begin.
Calendar startDate = Calendar.getInstance();
dateCalculator.setStartDate(startDate);
Set the span of how many working days the estimation is supposed to be calculated which in my case is 40 working days.
dateCalculator.moveByBusinessDays(40);
 To get the result use getCurrentBusinessDate() method.
dateCalculator.getCurrentBusinessDate();

0 comments:

 

©2009 Stay the Same | by TNB