如何比较两个Joda时间段 [英] How to compare two Joda time Periods
问题描述
这似乎并不太直接.
我正在尝试:
@Override
public int compare(Period o1, Period o2) {
return o1.toStandardDays().getDays() > o2.toStandardDays().getDays() ? -1 : (o1.toStandardDays().getDays() == o2.toStandardDays().getDays() ? 0 : 1);
}
但是我得到了这个例外:
But I get this exception:
java.lang.UnsupportedOperationException: Cannot convert to Days as this period contains months and months vary in length
at org.joda.time.Period.checkYearsAndMonths(Period.java:1455)
at org.joda.time.Period.toStandardDays(Period.java:1314)
我希望Peroid
将具有isLongerThan(Period p)
方法.
推荐答案
来自 Joda文档:
要比较两个期间的实际持续时间,请使用
toDuration
将这两个期间都转换为持续时间,该操作强调根据选择的日期结果可能有所不同.
To compare the actual duration of two periods, convert both to durations using
toDuration
, an operation that emphasises that the result may differ according to the date you choose.
这两个toDuration
方法是 BasePeriod#toDurationFrom(ReadableInstant)
.这意味着您必须选择该时间段的开始时刻或结束时刻,以便能够计算其持续时间.
The two toDuration
methods are BasePeriod#toDurationTo(ReadableInstant)
and BasePeriod#toDurationFrom(ReadableInstant)
. This means that you must choose either a start or end instant of this period in order to be able to compute its duration.
If that is a problem for you, then you might want to directly use Duration
instead of Period
.
这篇关于如何比较两个Joda时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!