3 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
5行代碼無循環(huán)的解決方案
定義之間的天數(shù)的方式與ChronoUnit.DAYS.between(start, end)表示4星期一至星期五之間存在天數(shù)的方式相同。由于我們只對(duì)工作日感興趣,因此我們必須減去周末,因此從星期五到星期二會(huì)有2工作日(只需計(jì)算endDay - startDay并減去2周末)。1如果要包含結(jié)果,則添加到結(jié)果中,即不要間隔幾天。
我提出兩種解決方案。
第一個(gè)解決方案(5線,簡(jiǎn)短和隱秘):
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;
}
添加回答
舉報(bào)