Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA java.util.Date to Mysql timestamp with wrong date value

Tags:

java

mysql

jpa

I have a JPA entity with a date field is persisted into Mysql DateTime.

Field:

  @Column(name = "CREATION_DATE")
  private Date creationDate;

Column:
CREATION_DATE datetime DEFAULT NULL,

Setter:

request.setCreationDate(new Date());//Value set to current date

I am getting an strange error that persisted date is 8 hours lesser than the current time. Tried few approaches as below:

  1. Using @Temporal(TemporalType.TIMESTAMP) for the field

  2. Setting default TimeZone
    TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));

  3. Printing the date before setting, which displays the correct value.

  4. Setting the timezone at mysql layer as well:
    SET GLOBAL time_zone = '+8:00'; SET SESSION time_zone = '+8:00';

  5. Changing the field type to java.sql.Timestamp

none of the above approaches helped. Anyone had a similar issue? Any clue?

like image 986
Ramprabhu Avatar asked Jun 30 '17 14:06

Ramprabhu


1 Answers

Found the issue, the problem was in jdbc connection URL.

spring.datasource.url=jdbc:mysql://:3307/dbname?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

due to the server time zone setting in the URL, GMT+8 time was converted to UTC which was leading to the 8 hours time difference. After removing the serverTimezone parameter in the URL, date is working fine. Thank you Neil and Shazin for your time and support.

like image 180
Ramprabhu Avatar answered Nov 03 '22 08:11

Ramprabhu