Calculate if today date between 2 other dates - But only with day and month [closed]
Use the java.time.MonthDay
class to represent the dates. It has methods like isAfter()
, isBefore()
and compareTo()
to compare two instances.
One problem is handling the case when the period covers a year change, that is, when the start date is after the end date.
boolean checkInterval(String testDate, String startDate, String endDate) {
var format = DateTimeFormatter.ofPattern("dd/MM");
var test = MonthDay.parse(testDate, format);
var start = MonthDay.parse(startDate, format);
var end = MonthDay.parse(endDate, format);
if (end.isBefore(start)) {
// end must be in *next* year
return !(test.isBefore(start) && test.isAfter(end));
} else {
// start and end on same year
return !(test.isBefore(start) || test.isAfter(end));
}
}
Since isAfter()
and isBefore()
returns false if the MonthDay
s are equal, the code is using ! isAfter()
instead of isBefore()
and vice-versa. (! isAfter()
will return true
if the MonthDay
s are equal or if the first (this
) is before the argument - mathematically x >= y
is the same as not(x < y)
)
Thats one way of doing it:
boolean isDateBetween(String dateToTest, String lowerDate, String upperDate) {
int anyYear = 2000;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate d1 = LocalDate.parse(lowerDate + "/" + anyYear, formatter);
LocalDate d2 = LocalDate.parse(upperDate + "/" + anyYear, formatter);
if (d2.isBefore(d1)) {
d1 = d1.minusYears(1);
}
LocalDate testDate = LocalDate.parse(dateToTest + "/" + anyYear, formatter);
return testDate.isEqual(d1) || testDate.isAfter(d1) && (testDate.isEqual(d2) || testDate.isBefore(d2));
}
Test:
boolean result1 = isDateBetween("17/01", "01/11", "19/01");
boolean result2 = isDateBetween("17/01", "06/06", "07/08");
System.out.println(result1);
System.out.println(result2);
Prints:
true
false
Haven't tested it properly, but it should work.