java 时间间隔 工作日_计算Java中两个日期之间的工作日数

76dd74e64f3d7ac23575049ca6372d6b.png

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) {    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;}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值