【发布时间】:2016-04-25 22:27:31
【问题描述】:
我有两个 JodaTime 对象,我想要这样的方法
// Return the latest of the two DateTimes
DateTime latest(DateTime a, DateTime b)
但我找不到这样的东西。我可以轻松编写它,但我确信 JodaTime 会在某个地方提供它。
【问题讨论】:
我有两个 JodaTime 对象,我想要这样的方法
// Return the latest of the two DateTimes
DateTime latest(DateTime a, DateTime b)
但我找不到这样的东西。我可以轻松编写它,但我确信 JodaTime 会在某个地方提供它。
【问题讨论】:
正如 Jack 所指出的,DateTime 实现了 Comparable。如果您使用 Guava,则最多两个日期(比如 a 和 b)可以通过以下简写方式确定:
Ordering.natural().max(a, b);
【讨论】:
DateTime 实现了Comparable,所以除了做之外你不需要自己动手:
DateTime latest(DateTime a, DateTime b)
{
return a.compareTo(b) > 0 ? a : b;
}
或直接使用 JodaTime API(考虑到 Chronology 不像 compareTo):
DateTime latest(DateTime a, DateTime b)
{
return a.isAfter(b) ? a : b;
}
【讨论】: