SpringBoot升级到2.0后默认时间格式变化_springboot接收date类型参数

x33g5p2x  于2021-11-27 转载在 Spring  
字(1.0k)|赞(0)|评价(0)|浏览(439)

springboot1.x时,请求返回默认将Date类型转换成时间戳:

createTime: 1544693261000

然而在升级到springboot2.0后,默认返回的时间格式变成了UTC字符串:

createTime: "2021-12-13T09:27:41.000+0000"

对于网页端或安卓端,UTC这种格式是不需要更改之前的代码的。但是,对于某些特殊平台,会造成时间显示出现问题(比如IOS端)。

需要将时间格式改回时间戳。

在SpringBoot配置中文件中加上如下配置即可:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: true

全局配置返回字符串

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

springboot接收date类型参数

springboot接收日期类型参数,实现自动转换。

当请求类型为json,date类型字段为 json 字段时,可以使用如下两种方法

1.当前参数加两个注解

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

2.全局配置
application.properties文件添加

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

还有一种:
参数改为String类型,在后端处理String到Date的转换,而不是交给SpringMVC来处理。

private void convertProperties(UserDO user, String dateStr) throws Exception {
        if (StringUtils.isNotBlank(expireDateStr)) {
            user.setdate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr));
        }
    }

相关文章

微信公众号

最新文章

更多