为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2019-09-24 10:52:07
谁能指出我一些Java摘录,让我可以在两个日期之间进行商务活动(星期六和星期日除外)。
查看完整描述

3 回答

?
www说

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;

}


查看完整回答
反对 回复 2019-09-24
  • 3 回答
  • 0 关注
  • 1813 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信