Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting date in UTC timezone when using Hibernate

I'm using Spring Boot and Hibernate 5 along with MySQL in my project.

How can I get a DateTime from the database in UTC instead of my JVM's timezone?

Is there any configuration to add to the application.properties like jadira.usertype.javaZone for Jadira or some other trick?

like image 802
error Avatar asked Dec 14 '22 07:12

error


2 Answers

Since Hibernate 5.2, you can now use the hibernate.jdbc.time_zone configuration property.

Basically, you can now force the UTC time zone for all TIMESTAMP and TIME columns using the following configuration property:

<property name="hibernate.jdbc.time_zone" value="UTC"/>
like image 66
Vlad Mihalcea Avatar answered Jan 06 '23 15:01

Vlad Mihalcea


To set UTC for all the date fields add following fields to MySQL connection string:

useTimezone=true
serverTimezone=UTC
useLegacyDatetimeCode=false

Example connection string:

jdbc:mysql://hostname/databaseName?useTimezone=true&amp;serverTimezone=UTC&amp;useLegacyDatetimeCode=false

AND

Use jadira user type to set UTC for a particular field

@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime",
    parameters = { @Parameter(name = "databaseZone", value = "UTC")})
private DateTime dateTime;
like image 34
Sanj Avatar answered Jan 06 '23 16:01

Sanj