1、問題描述
最近遇到了一個小問題,就是從數據庫中取出的時間總是和數據庫中存儲的時間有誤差,總是相差8個小時。
2、排查
2.1數據庫時區設定
看了好多博客,說是時區設定的問題。我在連接數據庫時也沒有做太多設定,就直接寫的
spring.datasource.url=jdbc:mysql://localhost:3306/guest?serverTimezone=UTC
然後根據 mybatis查詢mysql的datetime類型數據時間差了14小時(時區問題) 查看修改,使用如下指令
set global time_zone = '+8:00';
set time_zone = '+8:00';
flush privileges;
將數據庫的時區設置加八個小時,如圖
然而並不能解決我的問題。
又查看到[Mybatis] 讀取數據庫時間出現時間差這篇文章,覺得說得好像有點道理,因此我又將properties設置成爲如下的樣子
spring.datasource.url=jdbc:mysql://localhost:3306/guest?serverTimezone=UTC?useTimezone=true&serverTimezone=GMT%2B8
然而依然不起作用。
2.2 程序
既然到這裏還不能解決,那就只能排查程序了。
排查實體類的時候,我突然發現我使用了JsonFormat註解,點進去發現還要設置時區,否則的話就是使用默認時區UTC
/**
* {@link java.util.TimeZone} to use for serialization (if needed).
* Special value of {@link #DEFAULT_TIMEZONE}
* can be used to mean "just use the default", where default is specified
* by the serialization context, which in turn defaults to system
* default (UTC) unless explicitly set to another timezone.
*/
public String timezone() default DEFAULT_TIMEZONE;
所以我立馬就將註解加上時區,改爲
@JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone="GMT+8")
private Date endTime;
Thanks God! 終於好了
備註
後來我還發現,即使你的時區是錯誤的,當時當你轉換到前端顯示的時候,會自動轉換爲正確的時間:
@GetMapping("/getAll")
public ResponseEntity<List<User>> getAllGuest(){
return ResponseEntity.ok(managerService.getAllGuest());
}
這樣前端得到的值就是正確的時區轉換結果了。至於爲什麼,先挖個坑,有空來填。