Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a java class that represent a range between two instants?

Tags:

java

java-time

I do want to check if an Instant is between two other instants:

Currently I use:

import java.time.format.DateTimeFormatter;
import java.time.Instant;

Instant start = Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse("2016-10-25T12:31:39.084726218Z"));
Instant end = Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse("2016-10-25T13:31:39.084726218Z"));


// for exclusive range 
Instant testSubject1 = Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse("2016-10-25T12:31:40Z"));
boolean isInRange1 = testSubject1.isAfter(start) && testSubject1.isBefore(end); // this works as exclusive range

//for inclusive range
Instant testSubject2 = Instant.from(DateTimeFormatter.ISO_DATE_TIME.parse("2016-10-25T12:31:39.084726218Z"));
boolean isInRange2 = (testSubject2.equals(start) || testSubject2.isAfter(start)) && (testSubject2.equals(end) || testSubject2.isBefore(end)); // inclusive range

Is there any other utility function is the standard library or elsewhere that allows for this kind of range check is a simplified way?

I'm looking for something like:

new InstantRange(start,end).checkInstantWithin(testSubject1); 

// or

InstantUtils.inRangeExclusive(start,end, testSubject1);
InstantUtils.inRangeInclusivestart,end, testSubject1);

like image 217
RubenLaguna Avatar asked Sep 01 '26 06:09

RubenLaguna


1 Answers

You can use Interval in ThreeTen-Extra for a task like this. (Assuming you are willing o pull in a library)

like image 138
JodaStephen Avatar answered Sep 02 '26 22:09

JodaStephen