tags:

views:

404

answers:

5

So I'm using hibernate and working with an application that manages time. What is the best way to deal with times in a 24 hour clock?

I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning.

I'm using hibernate as well, just as an fyi

+4  A: 

Store them as long ts = System.currentTimeMillis(). That format is actually TimeZone-safe as it return time in UTC.

If you only need time part, well, I'm not aware of built-in type in Hib, but writing your own type Time24 is trivial -- just implement either org.hibernate.UserType or org.hibernate.CompositeUserType (load=nullSafeGet and store=nullSafeSet methods in them).

See http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom

But I'd still save absolute time anyway. May help in future.

P.S. That's all presuming storing Date is out of question for some reason. TimeZone in Date sometimes gets in the way, really. ;)

Vladimir Dyuzhev
dead link ` ` ` `
Juan Manuel
fixed the link.
Vladimir Dyuzhev
+1  A: 

Is there something wrong with using java.util.Date?

fd
java.util.Date is just a wrapper around the UTC long value, so often it's just as easy to just keep the long value yourself (see Vladimir Dyuzhev's answer).
Chris Carruthers
java.util.Date just uses the currentTimeMillis.
marcospereira
A: 

java.util.Date should be used; not a long (and definitely not a Calendar).

If you are using annotations be sure to use @Temporal

davetron5000
Why not use a long for time? Calendar would definitely not be appropriate.
DanielHonig
+1  A: 

I would suggest you look into using Joda, http://joda-time.sourceforge.net/, which offers much more intuitive and controllable time handling functionality than the core Date and Calendar implementations. JSR 310 is actually a proposition to include a new time API into java 7 that will be based largely on Joda. Joda also offers both timezone dependent Time handling and timezone independent time handling which eases difficulties when dealing with intervals.

Spencer Stejskal
JODA is a great API for date and time. I am already using it in the same application for dealing with Periods, that Java 1.5 does not deal with as well as Joda
DanielHonig
A: 

I also found another library recently that seems to be a response to JODA. http://www.date4j.net/

The advantages are listed on the project home page.

DanielHonig