简体   繁体   English

SpringBoot JPA时间存储在本地时区的MySQL中

[英]SpringBoot JPA time stored in MySQL in local time zone

I've written a class which looks like this 我写了一个看起来像这样的课程

@Entity
class Employee {

      @Column
      private String name;

      @Column
      private Date joinedDate;

}

Now, I assign value to joinedDate by doing new Date() . 现在,我通过执行new Date()将值分配给joinDate。 When I print this date, java will add the timezone correction to this. 当我打印此日期时,java将为此添加时区校正。 But Java will internally store time since epoch with no timezone. 但是,Java将自从纪元开始在内部存储时间,没有时区。 Let's say the local date was Wed Nov 29 18:43:43 IST 2017 假设当地日期是Wed Nov 29 18:43:43 IST 2017Wed Nov 29 18:43:43 IST 2017

When I store this object into database, what I expected to be stored was the time in GMT/UTC Zero timezone. 当我将此对象存储到数据库中时,我希望存储的是GMT / UTC零时区中的时间。 (or at least, storing the number of milliseconds since epoch). (或至少存储自纪元以来的毫秒数)。 But the value stored is Nov 29 18:43:43 . 但是存储的值是Nov 29 18:43:43

Which is wrong value. 这是错误的值。 Because it's not storing the UTC time and it's not storing the timezone either. 因为它不存储UTC时间,也不存储时区。 I expect within my application and DB dates should be stored in UTC timezone. 我希望在我的应用程序中,数据库日期应存储在UTC时区中。

I would like to store UTC value while reading and writing instead of timezone where the application is running. 我想在读写存储UTC值,而不是运行应用程序所在的时区。 My application could be running in different timezone but using the same database. 我的应用程序可能在不同的时区运行,但使用的是同一数据库。

How can I achieve this? 我该如何实现?

I think you must use the preferred type for java 8 java.time.ZonedDateTime that can storage nanosecond precisition and timezone. 我认为您必须为Java 8 java.time.ZonedDateTime使用首选类型,该类型可以存储纳秒级精度和时区。 Also be sure that in your database the type is TIMESTAMP. 另外,请确保数据库中的类型为TIMESTAMP。

You can check out examples in this page: enter link description here 您可以在此页面中查看示例: 在此处输入链接描述

By default java uses the machine timezone for date and calendar, if you want to change it then you have the follow options 默认情况下,java使用机器时区作为日期和日历,如果要更改它,则可以使用以下选项

Change JVM timezone 更改JVM时区

java -Duser.timezone=Europe/Sofia com.acme.Main

Create a date instance with a different timezone 创建具有不同时区的日期实例

Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()

Use java.time api 使用java.time api

Date convertedDatetime = Date.from(datetime.atZone(ZoneId.off("UTC").toInstant());

Obs: your observation is Right, the milliseconds since epoch have not timezone but you are using a date at the database, then it does. Obs:您的观察是正确的,自纪元以来的毫秒数没有时区,但是您正在数据库中使用日期,那么它确实是。


Update 更新资料

I found that answer , it promises to change only hibernate jdbc charset 我找到了答案 ,它承诺仅更改休眠的jdbc字符集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM