java timestamp 比较,将Date对象与Java中的TimeStamp进行比较

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(stamp));

assertTrue(date.compareTo(stamp) == 0);

assertTrue(stamp.compareTo(date) == 0);

assertTrue(stamp.equals(date));

I´ll be expecting a true, true, true, false. Because of this:

In the javadoc for java.sql.Timestamp, it states:

Note: This type is a composite of a java.util.Date and a separate

nanoseconds value. Only integral seconds are stored in the

java.util.Date component. The fractional seconds - the nanos - are

separate. The Timestamp.equals(Object) method never returns true when

passed a value of type java.util.Date because the nanos component of a

date is unknown. As a result, the Timestamp.equals(Object) method is

not symmetric with respect to the java.util.Date.equals(Object)

method. Also, the hashcode method uses the underlying java.util.Date

implementation and therefore does not include nanos in its

computation.

Due to the differences between the Timestamp class and the

java.util.Date class mentioned above, it is recommended that code not

view Timestamp values generically as an instance of java.util.Date.

The inheritance relationship between Timestamp and java.util.Date

really denotes implementation inheritance, and not type inheritance.

But instead I´ll get a true, false, true, false. Any ideas?

EDIT: This problem appear when a I was checking two Dates with the equals method, but one of the Date object come from a Hibernate class and debugging I see that the object contains a TimeStamp. So the equals method evaluate to false, then I found this: http://mattfleming.com/node/141

But when I try the code I get different results...if I can´t use neither equals and compareTo, what I should use to check if 2 Dates are the same?!?!

解决方案

Nican explained the equals part, about compareTo:

Timestamp has a compareTo(Date) method that converts it to Timestamp internally

Date does the comparison by downcasting (since Timestamp is a subclass of it); but as the javadoc states: "The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance"

Which of course is an horrible idea, in my opinion.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值