Posted
12 Oct 2008 @ 14:31

Categories
Tutorial, Java

Author
Alex

Bookmark
Delicious, Digg, reddit, StumbleUpon

Calculating Work Days In Java

In work this week I came across a couple of problems in which I needed to performs some calculations involving dates and a number of “work days” rather than just normal numbers of days. My first few attempts filed miserably, so I did some Googling to see if I could find anyone else that had come across the same problem and of course, there were plenty of people.

The code I eventually used I found shoehorned into the middle of a coding help forum and, with a little bit of tweaking, it calculated the number of whole work days in between two dates. The code is as follows;

public static int calculateDuration(Date startDate, Date endDate)
{
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startDate);

    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endDate);

    int workDays = 0;

    if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
    {
        startCal.setTime(endDate);
        endCal.setTime(startDate);
    }

    do
    {
        startCal.add(Calendar.DAY_OF_MONTH, 1);
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
        {
            workDays++;
        }
    }
    while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());

    return workDays;
}

This code solved my first problem, however I couldn’t find any code to solve my second problem, how to calculate a final date from a start date and a specified number of work days, to do the calculation I came up with the following code;

public static Date calculateEndDate(Date startDate, int duration)
{		
    Calendar startCal = Calendar.getInstance();

    startCal.setTime(startDate);
		
    for (int i = 1; i < duration; i++)
    {
        startCal.add(Calendar.DAY_OF_MONTH, 1);
        while (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
        {
            startCal.add(Calendar.DAY_OF_MONTH, 1);
        }
    }

    return startCal.getTime();
}

Hope this code works as well for you as it did for me.

Check back soon.

Update: Improved the calculating code with the suggestion from Anass (below) and made some more accuracy & business logic improvements to the ‘calculateDuration’ method. Enjoy.

Comments

anass / inptisto - 25 Nov 2008 @ 17:19

Hey my freind your second method is not working. you must replace the if by a while. regards

Add A Comment

Please login or signup in order to post comments.