【发布时间】:2019-04-10 01:23:32
【问题描述】:
检查两个Date() 对象是否相等,具有空安全功能的最佳方法是什么?
日期 d1
日期 d2
d1 = null, d2 = new Date() => equal false
d1 = null, d2 = null => equal true
d1 = SAME_INSTANT, d2 = SAME_INSTANT => equal true
d1 = new Date(), d2 = YESTERDAY => equal false
【问题讨论】:
-
d1 = new Date(), d2 = new Date()可能会在午夜时分返回false;) -
@Thomas 因为这是遗留的
Date类,它实际上表示以毫秒为单位的日期时间,因此每毫秒出现一次获得两个不相等实例的机会。在我的机器上,循环do {} while(new Date().equals(new Date()));在几毫秒(五到四十之间)内完成。 -
为什么还要使用
Date类?它的设计很糟糕,现在已经过时了。请改用java.time, the modern Java date and time API, 中的Instant。