SpringBoot 相关时区(TimeZone)设置

1.启动文件中的TimeZone设置:

public static void main(String[] args) {
        TimeZone timeZone = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(timeZone);
        SpringApplication.run(MatrixApplication.class, args);
    }

只对运行的console日志的时间影响。
2.数据连接字符串

jdbc:mysql://localhost:3306/gmall?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

对与读取到的时间会自动减去+8小时插入到数据库(如果数据库设置的utc+8的北京时间的),查询的时候

3.springboot 接口时间字段返回配置

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

对springboot rest接口时间字段生效。

  1. 时间格式化时区设置
    如果没有设置会使用程序运行系统的默认的时区。
SimpleDateFormat dd=new SimpleDateFormat("yyyy/MM/dd");
        log.info(TimeZone.getDefault().toString()); // 系统默认时区
        log.info(dd.getTimeZone().toString());//SimpleDateFormat 使用的时区
        log.info(dd.parse(dstr1).toString());
        //dd.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        dd.setTimeZone((TimeZone.getTimeZone("Australia/Sydney")));//设置指定时区解析
        log.info(dd.parse(dstr1).toString());

5.数据库时区设置:

show variables like '%time_zone%';
mysql> set time_zone='+8:00';

修改后 select 结果(timestamp)转换成相应timezone时间展示,DateTime字段不变化
插入的时间时转换相应的timezone时间插入

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容