# 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
{
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++)
{
while (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
{
Update: Improved the calculating code with the suggestion from Anass (below) and made some more accuracy & business logic improvements to the `calculateDuration` method. Enjoy.