Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to handle timezones in JPA?

800776Nov 5 2008 — edited Nov 5 2008
Hello!
I'm using JPA provided by TopLink Essentials library and PostgreSQL database server.
My entity class CDR has a java.util.Date field:
@Entity
public class CDR implements Serializable
{
   @Temporal(TemporalType.TIMESTAMP)
   private Date dateTime;
   //...
}
JPA created a table cdr with a column datetime of type 'timestamp without time zone'. This is exactly what I need: storing date and time in UTC (without any timezones). But there is a problem:
//...
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("GMT 0:00"));
CDR cdr = new CDR();
cdr.setDateTime(df.parse("2008-07-01 00:05:00.000"));
em.persist(cdr);
//...
The date "2008-07-01 00:05:00.000" will be saved in database as "2008-07-01 04:05:00.000" because I live in +4:00 time zone (in winter time) and this is the default on my system (in my country in summertime we live in +3:00 timezone).

Is there any way to tell to the EntityManager to use a custom timezone but not the default when It persists my objects?

I want to operate UTC time everywhere in my program, because I dont want to depend on any time offsets. I dont like to store dateTime in database as long type.

Maybe I should use GregorianCalendar class (instead of java.util.Date) which is set to GMT 0:00 time zone?

Please help.
Thank you.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 3 2008
Added on Nov 5 2008
1 comment
2,189 views