我确实要检查一个Instant是否在其他两个瞬时之间:

目前,我使用:

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



标准库或其他地方是否还有其他实用程序功能可以简化这种范围检查?

我正在寻找类似的东西:

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

// or

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

最佳答案

您可以在ThreeTen-Extra中使用Interval来完成这样的任务。 (假设您愿意加入图书馆)

10-07 19:23
查看更多