springboot Date时间类型返回/请求格式
1、数据库设计
字段名:date_time
类型:datetime
2、代码 entity
@Data
public class DataInfo implements Serializable {
private static final long serialVersionUID = 1L;
private Date dateTime;
}
3、问题
(1)返回DataInfo类型数据用于前端展示时,前端显示时间为时间戳,而不是数据库中显示的时间格式
(2)postman传参dateTime调用接口时报错
报错内容
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot deserialize value of type `java.util.Date`
from String \"2024-03-10 13:27:49\"
4、解决方法
为entity实体中成员变量加上如下注解即可
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
entity修改如下:
@Data
public class DataInfo implements Serializable {
private static final long serialVersionUID = 1L;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date dateTime;
}