加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java.sql.Timestamp比较错误?

发布时间:2020-12-14 05:23:16 所属栏目:Java 来源:网络整理
导读:参见英文答案 java.sql.Timestamp created from java.util.Date,why always before() it?2 你好,我有一个这样的代码片段: Date d1 = new java.sql.Timestamp(new Date().getTime());Thread.sleep(10);Date d2 = new java.sql.Timestamp(new Date().getTime(
参见英文答案 > java.sql.Timestamp created from java.util.Date,why always before() it?2
你好,我有一个这样的代码片段:
Date d1 = new java.sql.Timestamp(new Date().getTime());
Thread.sleep(10);
Date d2 = new java.sql.Timestamp(new Date().getTime());
System.out.println("Date1: " + d1);
System.out.println("Date2: " + d2);
System.out.println("Comparing times d1.t < d2.t: " + (d1.getTime() < d2.getTime()));
System.out.println("Comparing dates d1.before(d2): " + (d1.before(d2)));

输出如下所示:

Date1: 2013-03-26 11:04:01.093
Date2: 2013-03-26 11:04:01.103
Comparing times d1.t < d2.t: true
Comparing dates d1.before(d2): false

这个java.sql.Timestamp类怎么了?

是的,我看到了这一点:

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.

但是它的日期是< - >时间关系.

在我的例子中,我只有时间戳,而且行为是意想不到的

更新:回答

这样做的原因是before()方法是重载的,不会在java.sql.Timestamp中覆盖.
我期待着“超越”行为.
比较时间戳的正确方法是使用Timestamp变量,而不是日期.

这在Java核心中仍然是一个糟糕的设计决策,因为继承应该意味着Timestamp是一个日期,没有惩罚和例外.

解决方法

尝试使用Timestamp而不是Date,它会工作.
Timestamp d1 = new java.sql.Timestamp(new Date().getTime());

时间戳和日期都有自己的方法执行.核实.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读