5

Is there any standard Java implementation to represent a time range with FROM and TO? Actually I am using the following class.

I also looked at Instant.range() or Period, which are both not defining a time range or span, but calculating the duration of a period instead of saving the exact time range with FROM and TO.

public class TimeRange {

  private Instant from, to;

  public TimeRange(Instant from, Instant to) {
     this.from = from;
     this.to = to;
  }

  public Instant getFrom() {
     return from;
  }

  public void setFrom(Instant from) {
     this.from = from;
  }

  public Instant getTo() {
     return to;
  }

  public void setTo(Instant to) {
     this.to = to;
  }

  public boolean isProperlySet() {
     return from != null && to != null;
  }
}
alex
  • 5,516
  • 2
  • 36
  • 60
  • 4
    The [Threeten-extra library](http://www.threeten.org/threeten-extra/) contains an [Interval](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html) class. Does that cover your need? – Henrik Aasted Sørensen Sep 13 '17 at 07:50
  • 5
    I find the method `isProperlySet()` weird. Are you doing this for every object, that contains settable members? Why not just throwing or let throw an `Exception`? – Herr Derb Sep 13 '17 at 07:51
  • 2
    Or my lib Time4J with even more features, see [API](http://time4j.net/javadoc-en/net/time4j/range/SimpleInterval.html#between-java.time.Instant-java.time.Instant-). – Meno Hochschild Sep 13 '17 at 07:52
  • 3
    I agree with @HerrDerb. Verify the received `Instant`s in the constructor, e.g. `this.from = Objects.requireNonNull(from);`. – Henrik Aasted Sørensen Sep 13 '17 at 08:05
  • @Henrik: that won't work because the objects are not final – alex Sep 13 '17 at 08:49
  • Ah, the setters. I need more coffee. :) – Henrik Aasted Sørensen Sep 13 '17 at 08:50
  • @Herr Derb: The method can be used to do an ondemand validation from external code, so its convenient. Exceptions might be code in most cases, but here i want to check before instead of receiving exceptions to determine an detailed error cause which can be shown to the user – alex Sep 13 '17 at 08:50
  • I saw library, but isn't there a "JAVA-Standard" way to do this? I think its a common use case... – alex Sep 13 '17 at 08:52
  • @alex But still, you are using `isProperlySet()` so the developer can make sure that he is using this object correctly. That is a job for `Exceptions` and a correct `javaDoc`. – Herr Derb Sep 13 '17 at 09:04
  • `isProperlySet` avoids forcing the developer to do nullchecks, exception handling would force a lot unnecessary boiler plate code, so i would disagree here. – alex Sep 13 '17 at 09:40
  • Possible duplicate of [Is there a class in java.time comparable to the Joda-Time Interval?](https://stackoverflow.com/questions/22150722/is-there-a-class-in-java-time-comparable-to-the-joda-time-interval) –  Sep 13 '17 at 12:18

0 Answers0