JodaTime Interval irrespective of the year?

I'd like to have a JodaTime Interval which represents a range of days within a year. For example, January 21 - February 23 or the like, or even December 7 - January 13. Now I'd like to figure out if a given DateTime falls within that range of the year, regardless of the particular year.

Unfortunately, Interval#contains doesn't seem to work this way. For example, January 7, 2013 might match, but January 7, 1863 will not. Is there any workaround or another bit of the API I can use?

Jon Skeet
people
quotationmark

I don't believe there's any such type within Joda Time - and Interval deals with instants, where it sounds like you're interested in day/month values anyway.

You should probably construct your own type that is composed of two MonthDay fields.

Then to determine whether a particular value is within that range, extra the MonthDay for that value, and compare the three values to each other.

For example:

// Note: this assumes you always want end to be exclusive, and start to be inclusive.
// You may well want to make end inclusive instead; it depends on your use case.
public final class MonthDayInterval {
    private final MonthDay start;
    private final MonthDay end;

    public MonthDayInterval(MonthDay start, MonthDay end) {
        this.start = start;
        this.end = end;
    }

    public boolean contains(DateTime dateTime) {
        MonthDay monthDay = 
        return contains(new MonthDay(
            dateTime.getMonthOfYear(), dateTime.getDayOfMonth());
    }

    public boolean contains(MonthDay monthDay) {
        boolean natural = start.compareTo(monthDay) <= 0 && monthDay.compareTo(end) < 0;
        // We need to invert the result if end is after or equal to start.
        return start.compareTo(end) < 0 ? natural : !natural;
    }
}

people

See more on this question at Stackoverflow