@JsonFormat注解转换时间错误问题解决方案

在和前端小伙伴对接接口的时候,前端小伙伴问我能不能后台处理一下createTime的返回格式。如图:

image.png

我想,这很简单啊。就在后台返回的属性家加了@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")注解

@JsonFormat 简单介绍

@JsonFormat注解是一个时间格式化注解,比如我们存储在mysql中的数据是date类型的,当我们读取出来封装在实体类中的时候,就会变成英文时间格式,而不是yyyy-MM-dd HH:mm:ss这样的中文时间,因此我们需要用到JsonFormat注解来格式化我们的时间。
引入fasterxml maven jar包之后,就可以在实体类属性上面使用@JsonFormat注解了。要注意的是,它只会在类似@ResponseBody返回json数据的时候,才会返回格式化的yyyy-MM-dd HH:mm:ss时间,你直接使用System.out.println()输出的话,仍然是类似“Fri Dec 01 21:05:20 CST 2017”这样的时间样式。

    @ApiModelProperty(value = "下单时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

添加注解后,返回格式如下:

image.png

本来以为事情已经解决了,没想到前端小伙伴反馈时间不对,返回时间比真实下单时间早????
Google了一下,发现原来是时区的问题。
@JsonFormat 默认的时区是Greenwich Time, 默认的是格林威治时间,而我们是在东八区上,所以时间会比实际我们想得到的时间少八个小时。

解决方法:@JsonFormat加上timezone属性

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

    @ApiModelProperty(value = "下单时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createTime;

不过如果项目相关时间转换的很多,一个个添加timezone属性就有点麻烦了。在SpringBoot中我们可以使用如下配置,统一配置默认时区

/这里是Springboot 中的配置方式/
spring.jackson.time-zone=GMT+8 //设置为东八区
spring.jackson.time-zone=yyyy-MM-dd HH:mm:ss

发布了68 篇原创文章 · 获赞 19 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/tyjlearning/article/details/103023626
今日推荐