有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAsql。时间戳比较错误?

您好,我有这样一个代码片段:

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。时间戳类

是的,我看到了:

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中被重写。 我期待一个“覆盖”行为。 比较时间戳的正确方法是使用时间戳变量,而不是日期

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


共 (4) 个答案

  1. # 1 楼答案

    嗯,这似乎是一个文档不足的功能

    {}的{}和{}方法似乎与第二种方法进行比较,但没有考虑毫秒部分。试着运行它,直到两个TimeStamp都进入不同的秒数,并且比较按预期进行(将sleep增加到500以使其更容易)

    顺便说一下,compareTo方法考虑了毫秒数,因此您可以使用它

  2. # 2 楼答案

    尝试使用Timestamp而不是Date,它会起作用

    Timestamp d1 = new java.sql.Timestamp(new Date().getTime());
    

    TimestampDate都有自己的方法before的实现。检查一下

  3. # 3 楼答案

    如果调用方法Timestamp.before(Timestamp),将得到预期的结果

    但显然,使用Timestamp作为Date将是一个全面的混乱。您必须使用Timestamp作为Timestamp静态

  4. # 4 楼答案

    如前所述

    timestamp is a thin wrapper

    时间戳只是增加了保存SQL时间戳分数秒值的能力(在出现问题的情况下精度为纳秒)