Skip to content

Instantly share code, notes, and snippets.

@digitalpardoe
Created July 16, 2011 20:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save digitalpardoe/1086772 to your computer and use it in GitHub Desktop.
Save digitalpardoe/1086772 to your computer and use it in GitHub Desktop.
Calculating Work Days In Java
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;
}
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment