Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What time zone does Hibernate use when it reads and writes a Java Calendar object to an SQL TIMESTAMP?

When Hibernate writes a Java Calendar object to an SQL TIMESTAMP column, to which time zone does it adjust the date, that of the computer or that specified in the calendar object (or some other)?

When Hibernate reads the TIMESTAMP into the calendar object, to which time zone does it translate the date?

like image 438
Derek Mahar Avatar asked Nov 07 '10 10:11

Derek Mahar


People also ask

Does Java calendar have timezone?

The java. util. Calendar. getTimeZone() method gets the time zone.

How does Java handle time zones?

If you cannot change the OS or the JVM timezone, you can still convert a Java Date/Time or Timestamp to a specific time zone using the following two JDBC methods: PreparedStatement#setTimestamp(int parameterIndex, Timestamp x, Calendar cal) – to convert the timestamp that goes to the database.

Is timestamp stored with timezone?

The timestamp datatype allows you to store both date and time. However, it does not have any time zone data. It means that when you change the timezone of your database server, the timestamp value stored in the database will not change automatically.


1 Answers

When Hibernate writes a Java Calendar object to an SQL TIMESTAMP column, to which time zone does it adjust the date, that of the computer or that specified in the calendar object (or some other)?

Hiberante 3.x uses the following in the CalendarType (see HB-1006):

public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    final Calendar cal = (Calendar) value;
    //st.setTimestamp( index,  new Timestamp( cal.getTimeInMillis() ), cal ); //JDK 1.5 only
    st.setTimestamp( index,  new Timestamp( cal.getTime().getTime() ), cal );
}

So Hibernate uses PreparedStatement#setTimestamp(int, Timestamp, Calendar) which uses the time zone of the calendar.

When Hibernate reads the TIMESTAMP into the calendar object, to which time zone does it translate the date?

Well, again, let's look at the CalendarType class:

public Object get(ResultSet rs, String name) throws HibernateException, SQLException {

    Timestamp ts = rs.getTimestamp(name);
    if (ts!=null) {
        Calendar cal = new GregorianCalendar();
        if ( Environment.jvmHasTimestampBug() ) {
            cal.setTime( new Date( ts.getTime() + ts.getNanos() / 1000000 ) );
        }
        else {
            cal.setTime(ts);
        }
        return cal;
    }
    else {
        return null;
    }

}

So Hibernate constructs a default GregorianCalendar using the current time in the default time zone with the default locale.


As a side note, I highly suggest to read the following question:

  • Daylight saving time and Timezone best practices
like image 159
Pascal Thivent Avatar answered Sep 26 '22 20:09

Pascal Thivent