2

I am facing an interesting question. On my local environment, I am on PDT time. When I store a UTC Date from my front end and right before I store the Date into my MySQL database through Hibernate, I check the date in Java prior to it being stored and the Date is actually converted into whatever my System's time zone was. I was really curious why this was even though my Date in the front end was formatted in UTC date, so I changed my System time zone from PDT to EDT and the date on in Hibernate ended up being in EDT time next time I tried to store that date. Is there any way I can change it so that in all environments, the Date is stored in as UTC time if it is not already in the UTC time zone?

user1871869
  • 3,317
  • 13
  • 56
  • 106

2 Answers2

0

Back-end Side:

MySQL having the setTimestamp/getTimestamp code, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false, for further learning you can refer this document

For example, if your database is set to use UTC, there might be several possible UTC time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:

String url =
 "jdbc:mysql://localhost/databasename?useLegacyDatetimeCode=false&serverTimezone=UTC+05:30";

Client Side:

Put below code in web.xml file, It will take your sytem timezone and display time in UTC on web page..

<context-param>
   <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
   <param-value>true</param-value>
</context-param>

and set UTC Timzone for MySQL you can refer this link Should MySQL have its timezone set to UTC?

Community
  • 1
  • 1
Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28
0

Hibernate 5.2 simplifies this task as explained in this article.

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"/>
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911