我正在尝试在两个日期之间找到工作日计数(周末和时间必须忽略)。我正在使用以下功能来做到这一点。但它给出了多种情况的错误结果,例如,如果startdate是周末还是enddate是周末。这是一个示例,可以计算一天的额外日期。
2018-03-08 00:00:00.0和2018-04-22 01:37:29.887
计数返回32(应该是31,它也在考虑23-04-2018)。请提供一些完美的解决方案/方法来做同样的事情。
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;
}
我尝试了多种解决方案,但除了上述情况外,这种方法效果很好。
答案 0 :(得分:8)
我高度建议使用Java 9及更高版本中的java.time.LocalDate::datesUntil
方法。它只需要几行来计算,而不必使用Calendar
:
var startDate = LocalDate.parse("2018-03-08");
var endDate = LocalDate.parse("2018-04-22");
var numWeekDays = startDate.datesUntil(endDate)
.map(LocalDate::getDayOfWeek)
.filter(d -> d != DayOfWeek.SATURDAY && d != DayOfWeek.SUNDAY)
.count();
System.out.println(numWeekDays);
输出:
32