Search code examples
javadatejava-8localdatezoneddatetime

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

I am using java 8 and I want to check that the age of recordDate is greater than 5 days or not. But not from today but 5 days older than cobDate? How can I implement this and perhaps by using the already existing utility method I have that returns a ZoneDateTime? It should exclude weekends (e.g. Saturday & Sunday) and only consider business days.

Some Scenarios:

cobDate: 08/04/2021 recordDate: 08/04/2021 ==> false >> not older than 5 days

cobDate: 08/04/2021 recordDate: 31/03/2021 ==> true>> older than 5 days

cobDate: 08/04/2021 recordDate: 02/04/2021 ==> false >> not older than 5 days


Solution

  • 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;
        }
    

    From a very good article where I have just removed holidays check and added a constraint that endDate must always be after startDate

    calculate business days

    Then you can just do

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