简体   繁体   English

如何将时区正确设置为 UTC,以便以这种格式正确保存和检索所有时间戳?

[英]How to properly set timezone to UTC, so all timestamps are correctly saved and retrieved in this format?

In my spring boot (2.1.4) project I have mysql database (5.7.21 - version of server) and following application properties:在我的 spring boot (2.1.4) 项目中,我有 mysql 数据库(5.7.21 - 服务器版本)和以下应用程序属性:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC

and

hibernate.jdbc.time-zone=UTC . hibernate.jdbc.time-zone=UTC

Now when I save entitity records with @CreationTimestamp using java (either by using @PostConstruct or some controller/service logic) the dates are correctly converted to UTC timezone and saved do database, and also retrieved in UTC format (as I want them to be).现在,当我使用 java(通过使用@PostConstruct或某些控制器/服务逻辑)使用@CreationTimestamp保存实体记录时,日期被正确转换为UTC时区并保存在数据库中,并且还以UTC格式检索(因为我希望它们是)。 However, when I add (other) records through data.sql file.但是,当我通过data.sql文件添加(其他)记录时。 The corresponding timestamp fields have also UTC timezone, but this time the time is not properly converted to UTC (it's just my current time with timezone set to UTC).相应的时间戳字段也有 UTC 时区,但这次时间没有正确转换为 UTC(这只是我的当前时间,时区设置为 UTC)。

How to properly set it for both situations to always convert local time to UTC, save it and always retrieve it as UTC from database?如何在两种情况下正确设置它以始终将本地时间转换为 UTC、保存它并始终从数据库中将其检索为 UTC?

Should changing mysql global timezone fix the issue?更改 mysql 全局时区是否应该解决此问题?

Example:例子:

I am in timezone: GMT+2 The records saved at 11:11:53 have following time set for:我在时区:GMT+2 在 11:11:53 保存的记录的时间设置如下:

1.) Java created records: 09:11:53 1.) Java 创建的记录:09:11:53

2.) data.sql created records: 11:11:53 2.) data.sql 创建记录:11:11:53

Both are in UTC timezone (I can see it, when fetch in client), but only first is correct.两者都在 UTC 时区(我可以看到它,当在客户端获取时),但只有第一个是正确的。

Setting global timezone to UTC fixed the issue (all timestamps are now set to UTC , display in my local time in database, but get retrieved as UTC from database), what satisfies my conditions and is unified for both java and data.sql origin records.将全球时区设置为 UTC 解决了这个问题(所有时间戳现在都设置为UTC ,在我的本地时间显示在数据库中,但从数据库中检索为UTC ),满足我的条件并且对javadata.sql统一.

To do it on windows I had to download timezones sql file from here: https://dev.mysql.com/downloads/timezones.html要在 Windows 上执行此操作,我必须从此处下载时区 sql 文件: https : //dev.mysql.com/downloads/timezones.html

,and run: ,并运行:

mysql -D mysql -uroot -pmypassword < timezone_posix.sql
SET @@global.time_zone = UTC;

Also this post helped me a lot:这篇文章也对我有很大帮助:

How to set correct MySQL JDBC timezone in Spring Boot configuration 如何在 Spring Boot 配置中设置正确的 MySQL JDBC 时区

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

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