比较毫秒时java.util.Timestamp.after()错误了吗? [英] java.util.Timestamp.after() wrong when comparing milliseconds?
问题描述
我从Oracle数据库中提取日期。它们设置在java.util.Date字段上,它们实际上是java.sql.Timestamp实例(它是Java.util.Date的子类)。如果我通过在第一个日期调用after()并将它与第二个日期进行比较来比较两个不同数据库记录中的两个时间戳,那么除了毫秒之外,当日期的所有部分都相同时,我得到错误的答案。
I am pulling dates out of an Oracle database. They are set on a java.util.Date field and they are in reality java.sql.Timestamp instances (which is a subclass of Java.util.Date). If I compare two of these timestamps from two different database records by calling after() on the first date and compare it to the second, I get the wrong answer when all parts of the date are the same except for the milliseconds.
以下所有情况都会导致真实,但第二组数字不会:
All of the following should result in "true", however the second set of numbers does not:
firstDate = 1/1/2000 12:00:20:00
secondDate = 1/1/2000 12:00:10:00
result = firstDate.after(secondDate);
result is TRUE <-- EXPECTED RESULT
firstDate = 1/1/2000 12:00:00:10
secondDate = 1/1/2000 12:00:00:00
result = firstDate.after(secondDate);
result is FALSE <-- NOT EXPECTED, result should be TRUE
我知道nanos与Timestamp类中的Date实例分开存储,我很好奇这是否是问题。
I know nanos are stored separately from the Date instance in the Timestamp class and I am curious if this is the issue.
推荐答案
您可以比较它们,但只能通过比较毫秒。虽然它非常难看,但它似乎适用于所有情况(无论是 java.sql.Timestamp
还是 java.util.Date
)。
You can compare them, but only by comparing millis. While it's quite ugly, it seems to work in all cases (regardless of which is java.sql.Timestamp
or java.util.Date
).
if(date1.getTime() > date2.getTime()) {
//...
}
这篇关于比较毫秒时java.util.Timestamp.after()错误了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!