3 回答
TA贡献1775条经验 获得超8个赞
5行代码无循环的解决方案
定义之间的天数的方式与ChronoUnit.DAYS.between(start, end)表示4星期一至星期五之间存在天数的方式相同。由于我们只对工作日感兴趣,因此我们必须减去周末,因此从星期五到星期二会有2工作日(只需计算endDay - startDay并减去2周末)。1如果要包含结果,则添加到结果中,即不要间隔几天。
我提出两种解决方案。
第一个解决方案(5线,简短和隐秘):
import java.time.*;
import java.time.temporal.*;
public static long calcWeekDays1(final LocalDate start, final LocalDate end) {
final DayOfWeek startW = start.getDayOfWeek();
final DayOfWeek endW = end.getDayOfWeek();
final long days = ChronoUnit.DAYS.between(start, end);
final long daysWithoutWeekends = days - 2 * ((days + startW.getValue())/7);
//adjust for starting and ending on a Sunday:
return daysWithoutWeekends + (startW == DayOfWeek.SUNDAY ? 1 : 0) + (endW == DayOfWeek.SUNDAY ? 1 : 0);
}
第二种解决方案:
public static long calcWeekDays2(final LocalDate start, final LocalDate end) {
final int startW = start.getDayOfWeek().getValue();
final int endW = end.getDayOfWeek().getValue();
final long days = ChronoUnit.DAYS.between(start, end);
long result = days - 2*(days/7); //remove weekends
if (days % 7 != 0) { //deal with the rest days
if (startW == 7) {
result -= 1;
} else if (endW == 7) { //they can't both be Sunday, otherwise rest would be zero
result -= 1;
} else if (endW < startW) { //another weekend is included
result -= 2;
}
}
return result;
}
添加回答
举报