-1

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
michele
  • 26,348
  • 30
  • 111
  • 168
  • 3
    `d1 = new Date(), d2 = new Date()` might return `false` for a split second around midnight ;) – Thomas Nov 06 '18 at 16:01
  • 2
    @Thomas since this is the legacy `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 loop `do {} while(new Date().equals(new Date()));` completes in a few milliseconds (between five and forty). – Holger Nov 06 '18 at 16:14
  • Why do you still want to use the `Date` class? It’s poorly designed and now long outdated. Use `Instant` from [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) instead. – Ole V.V. Nov 06 '18 at 16:37

3 Answers3

8

Use Objects.equals(d1, d2):

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

Thomas
  • 174,939
  • 50
  • 355
  • 478
3

Since java-7, use:

Objects::equals

And stop using java.util.Date if you can; use Instant when you want Date - easier to work with and a lot less error prone.

Eugene
  • 117,005
  • 15
  • 201
  • 306
0
Optional.ofNullable(d1).map(d -> d.equals(d2)).orElseGet(() -> d2 == null);

Works when either is null

buræquete
  • 14,226
  • 4
  • 44
  • 89