7

Java 8 introduced a new Time & Date API, with classes like Period or Duration.

Now I'm looking for a class to represent date intervals, e.g. "from 4th August 2016 to 8th August 2016" and answer the question: do these intervals overlap. Period doesn't seem to satisfy this, since it works in an affine way, not knowing where the interval has started, only how long it takes.

Is there any Java 8 standard library class to suit my needs? Or do I have to write my own?

marmistrz
  • 5,974
  • 10
  • 42
  • 94
  • What are you trying to do with the start and end date time? Are you trying to work out the amount of time between the two? – Ben Green Apr 13 '16 at 14:24
  • You could try [Joda time interval](http://joda-time.sourceforge.net/apidocs/org/joda/time/Interval.html). Java 8 doesn't have an equivalent: http://stackoverflow.com/questions/22886030/equivalent-to-jodatime-interval-in-java-8-date-and-time-api – Compass Apr 13 '16 at 14:28
  • Java 8 has no interval class, but you might find my library interesting: [Time4J](http://time4j.net/javadoc-en/net/time4j/range/package-summary.html) It offers conversions for Java-8-types. – Meno Hochschild Apr 13 '16 at 14:30
  • Shouldn't `Duration` come close to what you need? – kucing_terbang Apr 13 '16 at 14:50
  • I'm not allowed to use any 3rd-party libs. I'll have `n` entries that some resource is reserved between two dates and have to find out whether will be free during some interval. – marmistrz Apr 13 '16 at 15:11
  • If 3rd-party-libs are not allowed then you have to create your own interval class from the scratch. Sorry for you. A simple approach would be a class with start and end date as members and defining some methods for creation, overlap-query, start- and end-query and the usual equals()-hashCode()-toString()-stuff. – Meno Hochschild Apr 13 '16 at 15:22
  • You could always copy & paste a library (not recommended but since you cannot use a 3rd party), which allows that (i.e., look at the license). There are several Interval (sometimes also called Range) implementations, e.g., Guava (https://github.com/google/guava/wiki/RangesExplained or Breinify (https://github.com/Breinify/brein-time-utilities/blob/master/docs/Interval.md) – Philipp Apr 26 '17 at 17:07

1 Answers1

2

You could resolve the date down into a long and use an IntervalTree. Here's one I made earlier.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213