I'm trying to find workday count between two dates (weekend and time have to ignore). I'm using following function to do that. But it is giving false results for multiple condition like if startdate is on weekend or enddate is on weekend. Here is one example for demo that giving one extra day in count.
2018-03-08 00:00:00.0 and 2018-04-22 01:37:29.887
Count returning 32 (Should be 31, it is considering 23-04-2018 as well). Please provide some perfect solution/approach to do the same.
private static int calculateDuration(Date startDate, Date endDate)
{
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
startCal.set( Calendar.HOUR_OF_DAY, 0 );
startCal.set( Calendar.MINUTE, 0 );
startCal.set( Calendar.SECOND, 0 );
startCal.set( Calendar.MILLISECOND, 0 );
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
endCal.set( Calendar.HOUR_OF_DAY, 0 );
endCal.set( Calendar.MINUTE, 0 );
endCal.set( Calendar.SECOND, 0 );
endCal.set( Calendar.MILLISECOND, 0 );
int workDays = 0;
if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
{
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do
{
startCal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("************"+Calendar.DAY_OF_WEEK);
System.out.println("Before weekend condition"+Calendar.DAY_OF_WEEK+"Workdays="+workDays);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
{
workDays++;
System.out.println("This day picked "+startCal.getTime()+"Workdays="+workDays);
}
}
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
System.out.println("Final workdays count for "+startDate+" and "+endDate+" is"+workDays);
return workDays;
}
I have tried multiple solutions but this worked well except mentioned scenario.