springboot输出时间和数据库中时间不一致问题
问题描述
数据库中存储的时间和我查库返给前端的时间不一致,例如差差八个小时
,差12个小时
等等。
基本知识介绍
CST、UTC 、GMT
参考介绍
测试demo
代码
public class TimeZoneTest {
public static void main(String[] args)throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("default ==> "+sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT ==> "+sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC ==> "+sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("CST"));
System.out.println("CST ==> "+sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
System.out.println("GMT+8 ==> "+sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
System.out.println("Asia/Shanghai ==> "+sdf.format(date));
Date parse = sdf.parse("2022-03-12 00:00:00");
System.out.println(sdf.format(parse));
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(parse));
}
}
结果
结论
问题解决
时区相关配置查看
1、看一下数据库时区
2、看一下springboot
的jdbc
连接
# 示例,这里我是 GMT
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT
3、看一下是否有jackson
依赖、是否有@JsonFormat
之类注解在属性上、是否存在全局配置如spring.jackson.time-zone=GMT+8
。
比对处理
jackson 全局配置同jdbc配置不一致
如果 spring.jackson.time-zone=GMT+8
、 serverTimezone=GMT
那么,最终返回结果会差8个小时。
jdbc 没有配置 serverTImezone
如果数据库时区为CST
,则返回结果少8个小时。
个人理解
参考
时区参考介绍