Compare Date object with a TimeStamp in Java

后端 未结 10 887
悲&欢浪女
悲&欢浪女 2020-12-09 02:32

When I test this code:

java.util.Date date = new java.util.Date();
java.util.Date stamp = new java.sql.Timestamp(date.getTime());

assertTrue(date.equals(sta         


        
10条回答
  •  渐次进展
    2020-12-09 03:20

    Sadly, the Timestamp class do overloads the equals(Object) method with equals(Timestamp) so comparisons on Timestamps are hard to do.

    In the equals(Object) javadocs says:

    Tests to see if this Timestamp object is equal to the given object. This version of the method equals has been added to fix the incorrect signature of Timestamp.equals(Timestamp) and to preserve backward compatibility with existing class files. Note: This method is not symmetric with respect to the equals(Object) method in the base class.

    My rule of thumb is never to compare timestamps for equality (which is pretty much useless anyway), but if you do have to check for equality, compare them using the result of getTime() (the number of milliseconds from january 1st 1970, 00:00).

提交回复
热议问题