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

Check if date is older than x days (business days only)

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 天?我该如何实现这一点,也许可以通过使用现有的实用方法来实现 returns a 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)
  }