-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
3
  • 3
    d1 = new Date(), d2 = new Date() might return false for a split second around midnight ;)
    – Thomas
    Commented Nov 6, 2018 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
    Commented Nov 6, 2018 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, instead.
    – Anonymous
    Commented Nov 6, 2018 at 16:37

3 Answers 3

9

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.

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.

0
Optional.ofNullable(d1).map(d -> d.equals(d2)).orElseGet(() -> d2 == null);

Works when either is null

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.