Forums Register Login

How to compare time reliably

+Pie Number of slices to send: Send
I found that java does not seem to have a very reliable way to do date/time comparison. Inspect the following sample code:

You probably would think that the date/time and millis returned by these two calendar should always be the same thus the compare result should always 0, but in fact, it doesn't. Sometimes it returns 0 sometimes -1... I spent a hack of time to find out this problem in my code (due to I wasn't even thought it could be wrong)

Here is a sample output:

the second one calc'ed 1 millisecond more. So if this isn't the prefer way to compare time in Java, what should I use?

Thanks!
[ March 02, 2008: Message edited by: jim xu ]
+Pie Number of slices to send: Send
When you use getInstance(), you get a Calendar set to the current time down to milliseconds. But when you call set, you are only setting year, month, date, hours, minutes, and seconds. The milliseconds remain unchanged.

To "zero out" the Calendar instance, call clear on it before setting it. Then you will get the result you are looking for...

Alternatively, you can set the milliseconds to whatever value you like using an overloaded set method...

[ March 02, 2008: Message edited by: marc weber ]
+Pie Number of slices to send: Send
Ah I see. Thanks!
Have you no shame? Have you no decency? Have you no tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 16461 times.
Similar Threads
Any Alternative for this CODE !!!!!!
Date Difference
J2ME accurate current time
Convert this to a date?
What fields does java.util.Date.equals compare?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:36:03.