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?
-
Have you config anything related to timezone in mysql? – dambros Apr 15 '16 at 08:21
-
@dambros no I haven't. What do you suggest be the best way I do that? I have a column in my database that can be used to store time zone potentially. – user1871869 Apr 15 '16 at 08:37
-
1Try the answer [here](http://stackoverflow.com/questions/930900/how-to-set-time-zone-of-mysql). – dambros Apr 15 '16 at 08:39
2 Answers
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?

- 1
- 1

- 2,181
- 3
- 13
- 28
-
Is there any way to actually change it so that it changes the timezone to UTC timezone instead of system timezone? – user1871869 Apr 15 '16 at 09:21
-
Set Your sytem timezone in UTC, Put above code in web.xml so it will show always system timezone to front end. – Piyush Gupta Apr 15 '16 at 09:23
-
I actually want it so that the backend always stores UTC time the front end doesn't matter to me. I also don't want to change my system timezone – user1871869 Apr 15 '16 at 09:24
-
-
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"/>

- 142,745
- 71
- 566
- 911