Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Timestamp.after() wrong when comparing milliseconds?

Tags:

java

time

oracle

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 

I know nanos are stored separately from the Date instance in the Timestamp class and I am curious if this is the issue.

like image 204
BestPractices Avatar asked Feb 23 '10 20:02

BestPractices


1 Answers

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()) {
  //...
}
like image 156
Konrad Garus Avatar answered Nov 10 '22 08:11

Konrad Garus