• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

How to compare time reliably

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
jim xu
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah I see. Thanks!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic