Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I express partial intervals using Joda-Time?

Tags:

java

jodatime

I have some data about opening hours I'm trying to represent using Joda-Time.

The typical opening hours of day look like this:

Open from 9 to 12, and from 13 to 20.

My main reason for representing them in Joda-Time entities, is to validate them:

  • Check that opening hours are valid (9 is before 12, etc)
  • Check that no open-intervals overlap ("9-12 and 11-13" are illegal)

API-wise, the Joda-Time Interval class has the methods I need for doing this validation, but Intervals are pairs of instants in the date-time-continuum. I would like to represent them independent of absolute time, kind of like an Interval of two LocalTime partials. Is this possible?

like image 309
Thomas Ferris Nicolaisen Avatar asked Jan 11 '12 10:01

Thomas Ferris Nicolaisen


1 Answers

Here's an attempt at a custom TimeInterval (pretty much like the solution Gray commented):

import org.joda.time.*;

public class TimeInterval {
    private static final Instant CONSTANT = new Instant(0);
    private final LocalTime from;
    private final LocalTime to;

    public TimeInterval(LocalTime from, LocalTime to) {
        this.from = from;
        this.to = to;
    }

    public boolean isValid() {
        try { return toInterval() != null; } 
        catch (IllegalArgumentException e) { return false;}
    }

    public boolean overlapsWith(TimeInterval timeInterval) {
        return this.toInterval().overlaps(timeInterval.toInterval());
    }

    /**
     * @return this represented as a proper Interval
     * @throws IllegalArgumentException if invalid (to is before from)
     */
    private Interval toInterval() throws IllegalArgumentException {
        return new Interval(from.toDateTime(CONSTANT), to.toDateTime(CONSTANT));
    }
}
like image 51
Thomas Ferris Nicolaisen Avatar answered Oct 27 '22 16:10

Thomas Ferris Nicolaisen