Read more : http://www.ehow.com/how_8498918_remove-title-blogger-pages.html

Saturday, 17 May 2014

Calculating Business days in Java

Hi ,

Some times we will get a requirement to calculate business days between given dates or days.
Below program explains you how we can achieve  working days(Business days) by excluding holidays in java.

In the below example I am considering only single day as holiday.
If you want to specify >1 holiday ,  you can use a list and  add all the holidays to list and use the list for calculation.


public class CalculatingBusinessDays {
      public static void main(String[] args) throws ParseException {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date date = dateFormat.parse("24/12/2012");// Specify the  a date

            int duration = 3;//Specify the duration how many days to increment
            //call the method to get the working days
            getWorkingDaysForADate(date, duration);

      }

      public static Date getWorkingDaysForADate(Date date, int duration) {
            Date dateValue = new Date();
            ArrayList<Integer> holidayList = new ArrayList<Integer>();
            /***************************
            * Holiday date is 25 Dec 2012 So we need to convert this day to actual
            * day in the year Use below code to convert actual date to a day in the
            * year
            *
             * SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
             * Date date = dateFormat.parse("25/12/2012");
            * Calendar cal = Calendar.getInstance();
            * cal.setTime(date)
            * cal.get(Calendar.DAY_OF_YEAR)
            *
             ************************************ */

            holidayList.add(360); // 360 is the integer Value of Holiday date(25 dec 2012)
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            for (int i = 0; i < duration; i++) {
                  cal.add(Calendar.DAY_OF_MONTH, 1);
                  while (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
                              || cal.get(Calendar.DAY_OF_WEEK) == cal.SUNDAY
                              || holidayList.contains((Integer) cal.get(Calendar.DAY_OF_YEAR))) {
                        cal.add(Calendar.DAY_OF_MONTH, 1);

                  }
            }
            dateValue=cal.getTime();
            /******************
            As per the logic we are incrementing days of the date by 3
             so, 24 +3 is 27 but the holiday date is 25 so we are excluding holiday from the day hence the new date
             is 28.
            **********************/
            System.out.println("Date  value is " +dateValue);
            return dateValue;
      }

}

No comments:

Post a Comment