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

时间:2021-04-08 10:11:44

标签: java date java-8 localdate zoneddatetime

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 天

1 个答案:

答案 0 :(得分:2)

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)
  }
相关问题