java - Mysql服务器保存LocalDateTime比操作系统时间晚3小时

标签 java mysql spring-boot spring-data-jpa

在服务将 LocaDateTime 写入数据库的过程中,在我的例子中,在带有 java 8 的 Spring Boot API 中,当保存在数据库端配置为 TIMESTAMP 的属性和 API 中配置为 LocaDateTime 的属性时,该日期将被保存保存时间比当前操作系统日期晚 3 小时。

假设我尝试在早上 10 点准确执行此操作,保存到数据库的日期应该是 11 小时,但在我的情况下,它不是这样工作的......

private LocalDateTime dataLimite;

@PrePersist
public void prepareToSave() {
    String str = "1986-04-08 10:00";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    this.dataLimite = dateTime.plusHours(1);
}

Date into the database 显然可能会注意到这是Mysql配置方面的问题,但是当我测试时......

SELECT NOW();

结果正是操作系统的日期和时间,那么发生的真正问题是什么?如何解决这个问题?

最佳答案

本地日期时间

更仔细地阅读文档。

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Java中的LocalDateTime类不能用来表示时刻。它代表大约 26-27 小时范围内的潜在时刻,即全局时区范围。

此类包含日期和时间,但故意缺少任何时区或相对于 UTC 的偏移量的概念。因此,例如,如果您存储今年 1 月 23 日的中午,我们不知道您是否指的是东京、加尔各答、巴黎或蒙特利尔的中午……所有不同的时刻,相隔几个小时,发生在东部较早,在东部较晚发生。西方。

所以你使用了错误的类。暂时使用 InstantOffsetDateTimeZonedDateTime

时间戳

仔细阅读文档。

MySQL 8 中的TIMESTAMP 类型类似于 SQL 标准类型TIMESTAMP WITH TIME ZONE。这种类型代表一个时刻,即时间线上的特定点。

文档 explains将提交到数据库的时刻调整为 UTC 进行存储。

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval.

这解释了你的问题。您隐式依赖当前默认时区来分配给 Java 中错误类型的对象,该对象缺少任何时区。 切勿编写依赖于服务器当前默认时区(或区域设置)的代码,因为这超出了程序员的控制范围。相反,请始终明确指定您想要/预期的时区。或者更好的是,尽可能使用 UTC 工作。

为了获得最佳结果,在与数据库交换值时请坚持使用 UTC。

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

myPreparedStatement.setObject( … , odt ) ;

检索。

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

要通过特定地区的人们使用的挂钟时间查看该时刻,请应用 ZoneId 来获取 ZonedDateTime

ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

Table of date-time types in Java (both modern and legacy) and in standard SQL.

关于java - Mysql服务器保存LocalDateTime比操作系统时间晚3小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984115/

相关文章:

java - Flume java.lang.IllegalStateException : File has changed size since being read

mysql - latin1_general_ci 和字符集 ISO-8859-15

java - @RequestParam Map<String, String> 在 Spring Boot 中打印变量名称作为键

mysql - SQL 查询 min(y) max(y) 和 X 组

php - 如何在 session 过期后自动更新数据库而不刷新我的页面

java - 通过 Spring Boot 加载属性文件进行映射

java - BeanCurrentlyInCreationException Spring Boot

java - Vaadin 中的多个 View 类

java - 如何在LWJGL中绘制透明纹理?

java - 尝试删除 xml 节点 - 错误