Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 DateTime check if period contains specific day

I want to check if a period of to dates contain the 29th of February.

private static final MonthDay LEAP = MonthDay.of(Month.FEBRUARY, 29);

i tried:

if (LEAP.isAfter(beginDate) && LEAP.isBefore(maturity)) {

    }

but beginDate and maturity are from the type LocalDate so the methods .isAfter and .isBefore can't be used.

Example

beginDate is 15.01.2012
maturity is 20.01.2013

during this period the 29th of February exists

Solution

I have finally found a solution:

for (int i = beginDate.getYear(); i <= maturity.getYear(); i++) {
    final Year year = Year.of(i);
    if (year.isLeap()) {
        if (beginDate.compareTo(LEAP.atYear(i)) <= 0 || maturity.compareTo(LEAP.atYear(i)) >= 0) {
            minMaturity.plusDays(1);
        }
    }
    return false;
}
like image 622
YvesHendseth Avatar asked Oct 16 '14 12:10

YvesHendseth


2 Answers

One way would be to create a TemporalAdjuster that returns the next 29th February and check if maturity is before or after that date. Example (not tested):

public static TemporalAdjuster nextOrSame29Feb() {
  return temporal -> {
    LocalDate input = LocalDate.from(temporal);
    if (input.isLeapYear()) {
      LocalDate feb29 = input.with(MonthDay.of(FEBRUARY, 29));
      if (!input.isAfter(feb29)) return feb29;
    }
    for (int year = input.getYear() + 1; ; year++) {
      if (Year.isLeap(year)) return LocalDate.of(year, FEBRUARY, 29);
    }
  };
}

And your code becomes:

boolean contains29Feb = !maturity.isBefore(beginDate.with(nextOrSame29Feb()));
like image 89
assylias Avatar answered Sep 18 '22 06:09

assylias


Have you tried converting the LocalDate and MonthDay to DateTime using toDateTimeAtStartOfDay and toDateTime respectively?

You need to test if this would result in true when the year is not a leap year. It might.

like image 38
John B Avatar answered Sep 20 '22 06:09

John B