@JsonFormat 跟 @DateTimeFormat
@JsonFormat 跟 @DateTimeFormat
1.前端 传给 后端。
当前端传来的是键值对,用@DateTimeFormat 规定接收的时间格式。
@ApiModelProperty(value = "创建时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
重点
当前端传来json串,后台用@ReuqestBody接收,必须用@JsonFormat 规定接收的时间格式。
@ReuqestBody 如果不使用@JsonFormat 接收空格会自动转换成 T 导致时间转化错误
报错详情
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not deserialize value of type
java.util.Date from String "2019-07-12T03:18:43.500Z": expected format "yyyy-MM-dd HH:mm:ss"
建议改成这样的格式
@ApiModelProperty(value = "创建时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
2、后端 传给 前端。
后端返回给前端的时间值,只能用@JsonFormat 规定返回格式
@ApiModelProperty(value = "创建时间")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
@DateTimeFormat 无法决定返回值的格式。
@JsonFormat 是jackson提供。
@DateTimeFormat 由spring提供。
原文链接:https://blog.csdn.net/liuguang212/article/details/106094668/
另:@JsonFormat 时区指定
1、默认时区是格林尼治时间(0时区)
2、指定的时区是字符串格式时间的时区
a: 前端传给后端时,日期由字符串格式转为Date类,此时指定时区是指转换前字符串的时区。
如,传入时间日期为"2021-03-23 10:40:30",未设置JsonFormat 的时区(默认时区),且系统的时区为东八区,
转换后时间日期为 "2021-03-23 18:40:30"。晚了八小时
b: 后端传给前端时,日期由Date类转为字符串格式,此时指定的时区是指转换后的字符串时区。
如,要将Date时间为“2021-03-23 10:40:30”格式化传到前端,未设置JsonFormat 的时区(默认时区),且系统的时区为东八区,
转换后时间日期为 "2021-03-23 02:40:30"。早了八小时

浙公网安备 33010602011771号