有没有办法用Java表示无限的未来/时间的结束? [英] Is there any way to represent infinite future / end of time in Java?

查看:183
本文介绍了有没有办法用Java表示无限的未来/时间的结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在,我一直在使用Instant.MAX表示无限的未来或时间的结束.例如,当计算时间戳集合的最小时间戳时:

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; 
}

但是我意识到使用Instant.MAX代表无限的未来"存在几个问题:

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

  • Instant.MAXOffsetDateTime.MAX
  • 不同
  • Instant.MAX.toEpochMilli()会引发ArithmeticException: long overflow,因此有时我会使用Instant.ofEpochMilli(Long.MAX_VALUE)而不是Instant.MAX,这不是很有意义的显示.
  • ...
  • 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.
  • ...

所以我想知道,是否有更好的方式在java.time.*或其他Java时间库中表示时间的结束?

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?

推荐答案

我们一直使用占位符,该占位符可用于sql,java和其他任何相关的编程语言.选择该占位符是可互操作的,并避免讨厌的问题,例如:

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()引发ArithmeticException

9999-12-31 00:00:00Z是我们使用的.它足够小以适合所有java.time类型和java.sql.Timestamp(尽管要注意时区问题).它足够大,可以有效地代表永远".您,我以及我们认识的每个人都将早已死掉,直到9999-12-31 00:00:00Z被认为是很快".

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

对于此特定用例,您不需要"max":

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.

这篇关于有没有办法用Java表示无限的未来/时间的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆