How to check if date is between interval in java?

I have six int variables: currentMonth, currentDay, monthFrom, dayFrom, monthUntil and dayUntil. I need to check if todays month and day falls within a range of from and until variables.

For example if currentMonth = 1, currentDay = 2, monthFrom = 11, dayFrom = 24, monthUntil = 3 and dayUntil = 3 the date is in the interval and the method should return true.

I'm not sure how to do it though. Is there any other option than to check every possible outcome using ifs?

Jon Skeet
people
quotationmark

I would suggest using java.time.MonthDay to represent each value involved. You then need to consider two alternative situations:

  • from is before or equal to until, in which case you need to perform a test of from <= current && current <= until.
  • from is later than until, in which case you need to perform a test of current <= until || current >= from

So:

public static boolean isBetween(
    int currentMonth, int currentDay,
    int fromMonth, int fromDay,
    int untilMonth, int untilDay)
{
    MonthDay current = MonthDay.of(currentMonth, currentDay);
    MonthDay from = MonthDay.of(fromMonth, fromDay);
    MonthDay until = MonthDay.of(untilMonth, untilDay);

    if (from.compareTo(until) <= 0)
    {
        return from.compareTo(current) <= 0 &&
            current.compareTo(until) <= 0;
    }
    else
    {
        return current.compareTo(until) <= 0 ||
            current.compareTo(from) >= 0;
    }
}

The two return statements could be combined, but it's probably simpler not to.

(This gives the same results as Marvin's code for his test cases.)

people

See more on this question at Stackoverflow