I don't see that java.util.Date class checks up to seconds.
Example posted in the previous post proves it. I am able to compare the dates without issues. The problem occurs when I am retrieving dates from database and the comparing them.
Meanwhile, I have done some interesting analysis on this.
As said, the date values are saved as datetime in database. When obtained them in java (code given below), we actually get a java.sql.Timestamp. The dates are then casted to java.util.Date as shown.
Timestamp saves milliseconds values in it's "nanos" field, which is not known to java.util.Date class.
When we call 'after' method on these dates, 'after' method of java.util.Date is called, which don't consider 'nanos' and hence giving the results unexpected.
You may refer the following methods
1. in java.util.Date:
Are we really talking about java.util.Date? I am guessing since you are getting it from DB it is a java.sql.Date. The Date class in sql package is a subclass of one in the util package but it zeros out the hours, minutes, seconds and milliseconds. Use java.sql.Timestamp instead to retain the full precision of time.
Joined: Mar 07, 2009
Vijitha Kumara wrote:
Ketan Mohite wrote:I don't see that java.util.Date class checks up to seconds.
Yes, It does.You can try it simply running following code inside a main method,
If you uncomment the commented lines you will get the output true, otherwise false (i.e: second Date object is one second after the first one).
That hardly proves your point. Look at the javadoc for java.util.Date it clearly states that Date has millisecond precision. The reason that you get true in your example is that the your computer is running fast enough two create two Date objects in the same millisecond, since the Date is precise up to millisecond only they are equal. Millisecond may seem very short to you but to your computer it is quite a long time period.
Joined: Feb 14, 2006
I meant to say that java.util.Date class also checks milliseconds, not just upto seconds.
In your code, you can reduce the sleep period and check the same.
Joined: Feb 14, 2006
Thanks for the responses guys. I understand the cause of the issue that I was facing, and commented the same in my second post.