Reputation: 946
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?
Upvotes: 5
Views: 14646
Reputation: 153730
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"/>
Upvotes: 9
Reputation: 946
Thank you all for your help, i tried Arul Kumaran and Sanj solutions but it's not working well. So i've chosen to store dates as varchar and use a converter to get it as a ZonedDateTime
Upvotes: 0
Reputation: 4029
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&serverTimezone=UTC&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;
Upvotes: 3
Reputation: 1539
You can get the date from the database and convert it to UTC
Date localTime = getDateFromDB();
String format = "yyyy/MM/dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
Upvotes: 1
Reputation: 1434
You can set the default timezone of your JVM to UTC when you start your app like
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
This will make sure the date is always in UTC when it moves around in your application, saved to db, retrieved from db etc.. and can be converted to any desired timezone when required.
Upvotes: 2