Java.util.Date behavior

Foo a; ... Date b = a.getDate(); Date c = new Date(b.getTime()); if (b.equals(c)) System.out.println("equal"); else System.out.println("not equal"); System.out.println(b.toString()); System.out.println(b.getTime()); System.out.println(c.toString()); System.out.println(c.getTime()); 

The above prints:

 not equal 2011-07-23 22:24:21.834 1311459861834 Sat Jul 23 22:24:21 1311459861834 

Why is this? Is this a date error? It's hard to believe.

+4
source share
3 answers

a.getDate() obviously returns java.sql.Timestamp

java.sql.Timestamp has a different equality method than java.uti.Date , which is basically

return obj instanceof Date && getTime() == ((Date) obj).getTime();

Timestamp however more complex and requires the target to also be Timestamp .

 if (ts instanceof Timestamp) { return this.equals((Timestamp)ts);//the impl checks nanos too } else { return false; } 

You are probably using Hibernate or something similar, which is saved by java.util.Date as a Timestamp .

+6
source

a.getDate() might not return java.util.Date , but something else that extends it.

This explains the strange behavior of b.toString() and b.equals(c) .

+4
source

This is only possible if a.getDate() returns a subclass of Date , such as java.sql.Date .

+2
source

All Articles