一、前台后台日期转换相差8小时

1、前台 \rightarrow 后台:

UTC:世界协调时间,也就是零时区的时间
CST:中国标准时间,中国是东八区,故比UTC大8小时

前台时间传到后台,通过jackson设置为UTC时区(详情见【注】),而Date类型为CST时区,故转换为Date类型后即UTC到CST的转换,所以加8小时。

【注】

如果你用过java8新的时间类下的Instant,查看toString方法会发现它使用DateTimeFormatter.ISO_INSTANT标准时间格式输出,如下:

Instant now = Instant.now();
// 2019-08-18T02:57:55.234Z

这个输出格式与我们上面的配置一致,所以就日期格式配置而言这本身并没有问题,下面我们再查看JacksonAutoConfiguration源码中configureDateFormat方法

private void configureDateFormat(Jackson2ObjectMapperBuilder builder) {
    String dateFormat = this.jacksonProperties.getDateFormat();
    if(dateFormat != null) {
        try {
            Class ex = ClassUtils.forName(dateFormat, (ClassLoader)null);
            builder.dateFormat((DateFormat)BeanUtils.instantiateClass(ex));
        } catch (ClassNotFoundException var6) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
            TimeZone timeZone = this.jacksonProperties.getTimeZone();
            if(timeZone == null) {
                timeZone = (new ObjectMapper()).getSerializationConfig().getTimeZone();
            }

            simpleDateFormat.setTimeZone(timeZone);
            builder.dateFormat(simpleDateFormat);
        }
    }
}

当我们没有配置时区时,它会执行timeZone = (new ObjectMapper()).getSerializationConfig().getTimeZone();,进一步查看timeZone属性,发现这其实是默认时区DEFAULT_TIMEZONE = TimeZone.getTimeZone("UTC")

看来问题的根源就在这儿,也就是说它其实用的是UTC时间。

2、后台 \rightarrow 前台:CST到UTC的转换,所以减去8小时。

3、解决办法:(如果不介意的话问题不大,因为前台传到后台的时间虽然多8个小时,但是后台传到前台的时间又减去了8小时,所以到前台的时间和用户输入的时间是一致的),若需要解决,则可以在yml中加上一下代码即可解决:GMT+8表示北京时间

spring:
    jackson:
        time-zone: GMT+8

二、数据库时区(有时候会出错

        对象保存到数据库后,有时候时间会差8小时,可通过设置serverTimezone=Asia/Shanghai

serverTimezone=GMT%2B8来解决。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐