Is there any way to represent infinite future / end of time in Java?

冷暖自知 提交于 2020-01-16 17:08:31

问题


Until now I've been using Instant.MAX to mean infinite future or end of time. For example when calculating the minimum timestamp of a collection of timestamps:

Iterator<Instant> it = ....

Instant minTs = Instant.MAX;
while(it.hasNext()) {
  Instant curr = it.next();
  minTs = curr.isBefore(minTs) ? curr : minTs; 
}

But I realized that there are several issues with using Instant.MAX to represent "infinite future":

  • Instant.MAX is not the same as OffsetDateTime.MAX
  • Instant.MAX.toEpochMilli() raises ArithmeticException: long overflow, so sometimes I use Instant.ofEpochMilli(Long.MAX_VALUE) instead of Instant.MAX which is not very intent-revealing.
  • ...

So I wonder, if there is a better way to represent the end of time in java.time.* or in other alternative java time library?


回答1:


We've always used a placeholder, one that works in sql, java, and whatever other programming language that's relevant. The placeholder is selected to be interoperable and to avoid annoying issues like:

Instant.MAX.toEpochMilli() raises ArithmeticException

9999-12-31 00:00:00Z is what we use. It's small enough to fit in all the java.time types and also in java.sql.Timestamp (though watch out for time zone issues). And it's big enough to effectively represent "forever". You, me, and everyone we know will be long dead before 9999-12-31 00:00:00Z is considered "soon".

For example when calculating the minimum timestamp of a collection of timestamps

For this specific use case, you don't need a "max":

Instant findMin(Iterator<Instant> iter) {
    if (!iter.hasNext()) {
        return null;
    }

    Instant minTs = iter.next();

    while (iter.hasNext()) {
        Instant curr = iter.next();

        minTs = ...;
    }

    return minTs;
}

Not sure if this use case is a real one or just something used to illustrate the problem.



来源:https://stackoverflow.com/questions/58808516/is-there-any-way-to-represent-infinite-future-end-of-time-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!