Question

I'm looking for a way to represent in Java a set of separated time periods that will support mathematical sets operations (union, intersection, etc).

Note that I'm expecting that sets that are the results of such operations will be merged into continuous time periods (as much as possible).

Example:

Say I have two of those hypothetical sets:

// imaginary constructor. numbers are unix times
TimeSet a = [(0,2), (3,6)]; 
TimeSet b = [(1,4), (5,7)];

Now lets perform some operations on them:

a.union(b);     // result = [(0,7)]
a.minus(b);     // result = [(0,1), (4,5)]
b.minus(a);     // result = [(2,3), (6,7)]
a.intersect(b); // result = [(1,2), (3,4), (5,6)]
a.diff(b);      // result = [(0,1), (2,3), (4,5), (6,7)]

No correct solution

OTHER TIPS

The best I've found is JodaTime's capabilities.

http://joda-time.sourceforge.net/apidocs/org/joda/time/Interval.html

The interval allows for methods like "abuts", "gap", and "overlap", which may then require additional conditional arithmetic.

Due to the lack of general support for such interval features in Java, I have decided to implement it with my library Time4J:

Moment d0 = Moment.of(0, TimeScale.POSIX);
Moment d1 = Moment.of(1, TimeScale.POSIX);
Moment d2 = Moment.of(2, TimeScale.POSIX);
Moment d3 = Moment.of(3, TimeScale.POSIX);
Moment d4 = Moment.of(4, TimeScale.POSIX);
Moment d5 = Moment.of(5, TimeScale.POSIX);
Moment d6 = Moment.of(6, TimeScale.POSIX);
Moment d7 = Moment.of(7, TimeScale.POSIX);

MomentInterval i1 = MomentInterval.between(d0,  d2);
MomentInterval i2 = MomentInterval.between(d3,  d6);
IntervalCollection<Moment> a = IntervalCollection.onMomentAxis().plus(i1).plus(i2);

MomentInterval i3 = MomentInterval.between(d1,  d4);
MomentInterval i4 = MomentInterval.between(d5,  d7);
IntervalCollection<Moment> b = IntervalCollection.onMomentAxis().plus(i3).plus(i4);

System.out.println(a.plus(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:02Z),[1970-01-01T00:00:01Z/1970-01-01T00:00:04Z),[1970-01-01T00:00:03Z/1970-01-01T00:00:06Z),[1970-01-01T00:00:05Z/1970-01-01T00:00:07Z)}

System.out.println(a.union(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:07Z)}

System.out.println(a.minus(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:01Z),[1970-01-01T00:00:04Z/1970-01-01T00:00:05Z)}

System.out.println(b.minus(a));
// {[1970-01-01T00:00:02Z/1970-01-01T00:00:03Z),[1970-01-01T00:00:06Z/1970-01-01T00:00:07Z)}

System.out.println(a.intersect(b)); 
// {[1970-01-01T00:00:01Z/1970-01-01T00:00:02Z),[1970-01-01T00:00:03Z/1970-01-01T00:00:04Z),[1970-01-01T00:00:05Z/1970-01-01T00:00:06Z)}

System.out.println(a.xor(b)); // your diff operator
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:01Z),[1970-01-01T00:00:02Z/1970-01-01T00:00:03Z),[1970-01-01T00:00:04Z/1970-01-01T00:00:05Z),[1970-01-01T00:00:06Z/1970-01-01T00:00:07Z)}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top