Spring Boot日期格式化

969 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

前言

在spring boot项目的开发过程中,后端默认接受的日期格式为yyyy-MM-dd'T'HH:mm:ss.SSSZ,但是我们比较习惯的格式为yyyy-MM-dd HH:mm:ss,如果按常用的格式就会报错。

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Invalid JSON input: Cannot deserialize value of type `java.util.Date` from String "2022-03-02 12:12:12": not a valid representation (error: Failed to parse Date value '2022-03-02 12:12:12': Cannot parse date "2022-03-02 12:12:12": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-03-02 12:12:12": not a valid representation (error: Failed to parse Date value '2022-03-02 12:12:12': Cannot parse date "2022-03-02 12:12:12": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
 at [Source: (PushbackInputStream);

解决方案

现在前后端分离项目,数据交互格式一般都是json,SpringMVC在做参数处理的时候,也就是HttpMessageConverter的时候,采用的是Jackson工具进行处理。如果要解决日期类型的字段因格式无法解析的情况,有如下几种情况处理。

  • 方案一

前段调整日期格式为yyyy-MM-dd'T'HH:mm:ss.SSSZ,也就是这样2022-06-011T00:00:00.000+0000

  • 方案二

在实体Date类型的字段上使用@JsonFormat注解格式化日期。注意引入的包是com.fasterxml.jackson.annotation.JsonFormat

import com.fasterxml.jackson.annotation.JsonFormat;

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

或者

import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;

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

以上的方式需要一个一个的进行配置,这个适合老项目,不能全局进行修改,因为可能有的人就是按yyyy-MM-dd'T'HH:mm:ss.SSSZ格式进行时间的格式化的。

  • 方案三

通过配置文件进行统一配置处理。

spring.jackson.default-property-inclusion=always
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyy-MM-dd HH:mm:ss

扩展

下面列举一些关于json序列化的注解。不过很少能用到。对json的操作推荐还是通过一些工具类自己实现。

  • @JsonIgnoreProperties此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。@JsonIgnoreProperties(value = { "word" })

  • @JsonIgnore此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

  • @JsonSerialize此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。@JsonSerialize(using = CustomDoubleSerialize.class)

  • @JsonDeserialize此注解用于属性或者setter方法上。用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize@JsonDeserialize(using = CustomDateDeserialize.class)