Ramprabhu
Ramprabhu

Reputation: 195

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

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?

Upvotes: 6

Views: 5347

Answers (1)

Ramprabhu
Ramprabhu

Reputation: 195

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.

Upvotes: 4

Related Questions