@JsonFormat @DataTimeFormat 时间格式
省流:用@JsonFormat即可
有时候会看到入参dto里,在时间类型的变量上用@DateTimeFormat,代码如下。
public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")private Date startDate;
}
这是为了入参传日期格式的值。即前端给后端传日期,如 {"startDate":"2022-01-01 01:02:02"}。如果没有@DateTimeFormat,会报错。
Invalid JSON input:
Cannot deserialize value of type `java.util.Date` from String "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": 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 "2023-02-01 01:02:03": not a valid representation (error: Failed to parse Date value '2023-02-01 01:02:03': Cannot parse date "2023-02-01 01:02:03": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
根据报错信息,while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ',传入的值日期格式有问题。正确格式:2023-02-01T00:00:00.000+0800,即前端传参 {"startDate":"2023-02-01T00:00:00.000+0800"}。
所以有人会用@DataTimeFormat。
但@DataTimeFormat不如@JsonFormat好用。另,如果值是纯日期,例如2022-01-01,不需要用注解。
@DataTimeFormat用于前端传后端,@JsonFormat用于后端传前端,这种说法是错误的。@JsonFormat前传后、后传前都可以用。
@JsonFormat
com.fasterxml.jackson.annotation.JsonFormat;
public class XXXdto{@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private Date startDate;
}
@DataTimeFormat
org.springframework.format.annotation.DateTimeFormat
public class XXXdto{@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date startDate;
}
@JsonFormat 和 @DateTimeFormat 区别
@JsonFormat | @DateTimeFormat | |
转换前端传入后端的时间格式的值 | √ | √ |
约束后端响应前端的时间类型的值 | √ | × |
数据类型(前端提交到后端) | 必须json 用@RequestBody | 必须form表单 不用@RequestBody |
时区 | √ | × 响应给前端的时间会比实际时间晚8个小时 |
补充:
1.前端传值给后端,后端接收到的都是字符串。
2.前端传日期格式的值,如果形如yyyy-MM-dd,即{"startDate":"2023-01-02"},不需要用@DataTimeFormat和@JsonFormat,框架会帮你转。
参考
不要在听大坑们@DateTimeFormat 和 @JsonFormat只是前后端传参的区别了_*阿莫西林*的博客-CSDN博客
SpringBoot中时间格式化的5种方法!