计算两个 Java 日期实例之间的差异
我在 Scala 中使用 Java 的 java.util.Date
类,想要比较 Date
对象和当前时间.我知道我可以使用 getTime() 计算增量:
I'm using Java's java.util.Date
class in Scala and want to compare a Date
object and the current time. I know I can calculate the delta by using getTime():
(new java.util.Date()).getTime() - oldDate.getTime()
然而,这给我留下了一个 long
代表毫秒.有没有更简单、更好的方法来获得时间增量?
However, this just leaves me with a long
representing milliseconds. Is there any simpler, nicer way to get a time delta?
不幸的是,JDK Date
API 严重损坏.我建议使用 Joda 时间库.
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Joda Time 有一个时间概念间隔:
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
顺便说一句,Joda 有两个概念:Interval
表示两个时间瞬间之间的时间间隔(表示上午 8 点到 10 点之间的时间),以及 Duration
> 表示没有实际时间界限的时间长度(例如表示两个小时!)
By the way, Joda has two concepts: Interval
for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration
that represents a length of time without the actual time boundaries (e.g. represent two hours!)
如果您只关心时间比较,大多数 Date
实现(包括 JDK 的实现)都实现了 Comparable
接口,该接口允许您使用 Comparable.compareTo()
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()