计算Java中两个日期之间的工作日数

谁能指出我一些Java摘录,让我可以在两个日期之间进行商务活动(星期六和星期日除外)。



手掌心
浏览 1814回答 3
3回答

www说

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) {&nbsp; &nbsp; final DayOfWeek startW = start.getDayOfWeek();&nbsp; &nbsp; final DayOfWeek endW = end.getDayOfWeek();&nbsp; &nbsp; final long days = ChronoUnit.DAYS.between(start, end);&nbsp; &nbsp; final long daysWithoutWeekends = days - 2 * ((days + startW.getValue())/7);&nbsp; &nbsp; //adjust for starting and ending on a Sunday:&nbsp; &nbsp; return daysWithoutWeekends + (startW == DayOfWeek.SUNDAY ? 1 : 0) + (endW == DayOfWeek.SUNDAY ? 1 : 0);}第二种解决方案:public static long calcWeekDays2(final LocalDate start, final LocalDate end) {&nbsp; &nbsp; final int startW = start.getDayOfWeek().getValue();&nbsp; &nbsp; final int endW = end.getDayOfWeek().getValue();&nbsp; &nbsp; final long days = ChronoUnit.DAYS.between(start, end);&nbsp; &nbsp; long result = days - 2*(days/7); //remove weekends&nbsp; &nbsp; if (days % 7 != 0) { //deal with the rest days&nbsp; &nbsp; &nbsp; &nbsp; if (startW == 7) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result -= 1;&nbsp; &nbsp; &nbsp; &nbsp; } else if (endW == 7) {&nbsp; //they can't both be Sunday, otherwise rest would be zero&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result -= 1;&nbsp; &nbsp; &nbsp; &nbsp; } else if (endW < startW) { //another weekend is included&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result -= 2;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java