当前位置: 代码迷 >> 综合 >> SpringBoot 存入数据库的时间与现实时间的有差别 (时区问题)
  详细解决方案

SpringBoot 存入数据库的时间与现实时间的有差别 (时区问题)

热度:55   发布时间:2023-10-08 17:30:50.0

最近在写简单的新增功能时发现,数据库写入前时间总和实际写入到数据库中的时间,有很大的差别的。

最后发现是由于时区导致的:

最初数据库连接配置:

spring.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.master.url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.master.username=root
spring.datasource.master.password=123456

 jdbc:mysql://localhost:3306/abc?serverTimezone=UTC

UTC代表的是全球标准时间 ,但是我们使用的时间是北京时区也就是东八区,领先UTC八个小时。

 解决办法:

          serverTimezone=Asia/Shanghai

# 主数据源
spring.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.master.url=jdbc:mysql://localhost:3306/abc?serverTimezone=Asia/Shanghai&allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.master.username=root
spring.datasource.master.password=123456