Alberto Pareja-Lecaros wrote:When you do a comparison of dates by object you are comparing the objects themselves, meaning everything about the object and their memory addresses.
No, that's not true at all. Read
the documentation.
Alberto Pareja-Lecaros wrote:
This
may return null, simply because the two constructors did not execute at exactly the same time. Or it may return true, because the execution times were close enough that they rounded to the same time in milliseconds. (A few years ago, most systems I worked on usually rounded to the nearest multiple of 10 milliseconds. I don't know how common that is now.)
Alberto Pareja-Lecaros wrote:If you want to compare the dates themselves, you have to check if the hour is the same, and the year is the same, and the second is the same, etc.
No. Just call equals(). A java.util.Date really has only
one field, a long value equal to the number of milliseconds since the beginning of Jan 1, 1970, GMT. As Rob just showed. That's all that should need to be compared.
Alberto Pareja-Lecaros wrote:Otherwise get the milliseconds elapsed of each object and compare those values.
Exactly. So why waste time with the other field?
Except...
As Paul C said several times, the specific classes of the Date objects may be different. Often a database will return its own custom subclass of Date, which may not correctly obey the API set forth in java.util.Date.equals(). Or, another common situation is that one of your Date objects may have had its value rounded off at some point. For example, our Oracle system usually rounds dates to the nearest second. (Or truncates them; I forget.) I think that's standard behavior unless you declare the column as TIMESTAMP. So when you retrieve a value from the DB, the last three digits of getTime() are 000. If you want to compare dates that have been thus rounded, you can do some simple math to round both times accordingly.
Siegfried: I would suggest, next time you have two dates that you think shoudl be equal, but they're not: first use getClass() to identify what class each Date really is. Then print the value of getTime() for each date. You may well see that one or more millisecond values have been rounded off. Based on what you observe, you can round off both millisecond values, before comparing them.