springboot数据库查询时出现时区差异问题怎么解决

    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”)

    以上就是springboot数据库查询时出现时区差异问题怎么解决的详细内容,更多请关注www.sxiaw.com其它相关文章!