如何解决springboot数据库查询时出现的时区差异问题

作者:这小呆 时间:2024-01-26 01:53:01 

springboot数据库查询时出现的时区差异

最近项目中使用到多数据源将MySQL库中的数据迁移到mongo库中,发现取出后的数据与原数据时间上会出现8小时的相差,

最后度娘后终于解决问题,记录一下:

网上看到了两种比较实用的方法,因为使用的springboot原因,所以我这里使用的是在配置文件application.yml中进行修改,另外其他方法网上都可以搜到,

1.在连接数据库的配置上我们添加一项

&serverTimezone=GMT%2b8
 primary:
      jdbc-url: jdbc:mysql://******:3306/***?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8
      username: ****
      password: *****
    secondary:
      jdbc-url: jdbc:mysql://*******:3306/***?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8
      username: *****
      password: ********

原格式应该是这样的:

&serverTimezone=GMT+8 这里使用%2b替换 + 号

2.直接在boot配置文件中增加jackson配置

#在application.yml中增加配置
spring:
    jackson:
        time-zone: GMT+8

这样就可以成功将时间修改成功了,还有其他方法,大家可以查阅哦

springboot new Date()时区差8小时

1 在k8s环境中,在代码中比较时间。new Date() 下相差8小时

检查宿主机 时区是 cst时区

用java代码写出controller时区发现是GMT

代码如下:

Calendar calendar = Calendar.getInstance();      
        System.out.println("目前时间:" + calendar.getTime());
        System.out.println("Calendar时区::" + calendar.getTimeZone().getID());
        System.out.println("user.timezone:" + System.getProperty("user.timezone"));
        System.out.println("user.country:" + System.getProperty("user.country"));
        System.out.println("默认时区:" + TimeZone.getDefault().getID());

输出时区是 GMT 跟宿主机还不一样,搞不定运维,自己搞把

看来还是时区搞的鬼-

1、数据库链接db添加参数 serverTimezone=Asia/Shanghai

2、springboot启动脚本添加 -Duser.timezone=GMT+08

3、jackson 全局配置

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone: GMT+8

4、jackson 注解

@JsonFormat(timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)

来源:https://blog.csdn.net/qq_35501880/article/details/102736685

标签:springboot,数据库,查询,时区差异
0
投稿

猜你喜欢

  • python实现批量获取指定文件夹下的所有文件的厂商信息

    2021-12-14 20:42:27
  • mysql慢查询的分析方法

    2010-08-03 14:51:00
  • python神经网络特征金字塔FPN原理

    2023-12-20 02:21:01
  • python+pyqt实现右下角弹出框

    2023-09-07 16:04:22
  • Date对象格式化方法

    2009-11-16 13:17:00
  • element弹窗表格的字体模糊bug解决

    2024-04-18 10:53:25
  • python 获取字典特定值对应的键的实现

    2022-07-01 19:25:21
  • python自动下载图片的方法示例

    2022-01-03 06:32:44
  • Python 中闭包与装饰器案例详解

    2021-08-08 12:28:32
  • accept-charset与Header P3P

    2009-04-01 18:43:00
  • python截取两个单词之间的内容方法

    2022-06-02 01:48:46
  • 分享4个Python中的非常好用的自动化脚本

    2023-12-03 09:59:17
  • python八皇后问题的解决方法

    2022-11-04 17:48:59
  • 详解selenium + chromedriver 被反爬的解决方法

    2022-03-20 18:40:46
  • 基于python的Paxos算法实现

    2023-04-15 07:40:58
  • PyTorch中torch.utils.data.DataLoader简单介绍与使用方法

    2023-10-30 07:12:00
  • Pytorch GPU显存充足却显示out of memory的解决方式

    2022-05-20 18:56:58
  • Python的迭代器和生成器

    2022-04-29 17:56:09
  • CSS背景属性5个应用实例

    2009-09-13 20:54:00
  • SQL Server数据库定时自动备份

    2024-01-13 22:01:25
  • asp之家 网络编程 m.aspxhome.com