问题
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 asOffsetDateTime.MAX
Instant.MAX.toEpochMilli()
raisesArithmeticException: long overflow
, so sometimes I useInstant.ofEpochMilli(Long.MAX_VALUE)
instead ofInstant.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()
raisesArithmeticException
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