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.2012maturity
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;
}
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()));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With