检查日期是否早于 x 天仅限工作日

问题描述

public class App {

    public static void main(String[] args) {
        final String cobDate = "2021-04-08";
        final String recordDate = "2020-12-01";
    }

    public static zoneddatetime getDate(String date,DateTimeFormatter formatter) {
        LocalDate localDate = LocalDate.parse(date,formatter);
        return localDate.atStartOfDay(ZoneId.of(ZoneOffset.UTC.getId()));
    }
}

我正在使用 java 8,我想检查 recordDate 的年龄是否大于 5 天。但不是从今天开始而是比 cobDate 早 5 天?我如何实现这一点,也许通过使用我已经存在的返回 ZoneDateTime 的实用程序方法?它应该排除周末(例如周六和周日),只考虑工作日。

一些场景:

cobDate: 08/04/2021 记录日期:08/04/2021 ==> false >> 不超过 5 天

cobDate: 08/04/2021 记录日期:31/03/2021 ==> true>> 超过 5 天

cobDate: 08/04/2021 记录日期:02/04/2021 ==> false >> 不超过 5 天

解决方法

private static long countBusinessDaysBetween(LocalDate startDate,LocalDate endDate) 
    {
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("Invalid method argument(s) to countBusinessDaysBetween(" + startDate
                    + "," + endDate);
        }

        if (startDate.isAfter(endDate)) {
           throw new IllegalArgumentException("Start Date must be before End Date");
        }
 
        Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY
                || date.getDayOfWeek() == DayOfWeek.SUNDAY;
 
        long daysBetween = ChronoUnit.DAYS.between(startDate,endDate);
 
        long businessDays = Stream.iterate(startDate,date -> date.plusDays(1)).limit(daysBetween)
                .filter(isWeekend.negate()).count();
        return businessDays;
    }

来自一篇非常好的文章,我刚刚删除了假期检查并添加了一个约束,即 endDate 必须始终在 startDate 之后

calculate business days

然后你就可以了

public boolean isOlderThanXDays(int xDays,LocalDate startDate,LocalDate endDate) {
      return (YourClassName.countBusinessDaysBetween(startDate,endDate) > xDays)
  }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...