Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Date's 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 bug in Date? Thats hard to believe.

like image 616
Arjun Singri Avatar asked Dec 16 '22 11:12

Arjun Singri


1 Answers

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

java.sql.Timestamp has different equals method than java.uti.Date which is basically

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

Timestamp however is more sophisticated and it requires the target to be Timestamp too.

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

You probably use Hibernate or something similar that persists java.util.Date as Timestamp.

like image 199
2 revs, 2 users 79% Avatar answered Jan 03 '23 15:01

2 revs, 2 users 79%