Which is the best way for checking if two Date()
object are equals, with null safe feature?
Date d1
Date 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()
might returnfalse
for a split second around midnight ;)Date
class, it actually represents a date-time in milliseconds, so the chance of getting two un-equal instances arises once every millisecond. On my machine, the loopdo {} while(new Date().equals(new Date()));
completes in a few milliseconds (between five and forty).Date
class? It’s poorly designed and now long outdated. UseInstant
fromjava.time
, the modern Java date and time API, instead.