直接接收前端String类型日期格式报错
首先在实际开发中处理日期时间格式时不可避免的事情,最常见的场景见于接口层,如下面所示
@Data
public class CmsTopicComment implements Serializable {
private Long id;
private String memberNickName;
private Long topicId;
private String memberIcon;
private String content;
private Date createTime;
private Integer showStatus;
}
上面CmsTopicComment类中字段createTime是Date时间格式,如果我们写一个Controller层
@GetMapping("/test")
public CommonResponse test(CmsTopicComment cmsTopicComment){
log.info("接收参数:{}",cmsTopicComment);
log.info("接收日期:{}",cmsTopicComment.getCreateTime());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info("日期格式转换:{}",format.format(cmsTopicComment.getCreateTime()));
return CommonResponse.success(cmsTopicComment);
}
通过APiPost去调用接口
http://localhost:8089/topic/test
{
"createTime":"2020-10-20 10:20:20"
}
请求参数解析时会报错:
{
"success": false,
"code": "402",
"msg": "请求参数异常",
"data": "JSON parse error: Cannot deserialize value of type `java.util.Date` from String \"2020-10-20 10:20:20.6666\": not a valid representation (error: Failed to parse Date value '2020-10-20 10:20:20.6666': Cannot parse date \"2020-10-20 10:20:20.6666\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String \"2020-10-20 10:20:20.6666\": not a valid representation (error: Failed to parse Date value '2020-10-20 10:20:20.6666': Cannot parse date \"2020-10-20 10:20:20.6666\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))\n at [Source: (PushbackInputStream); line: 1, column: 34] (through reference chain: com.fairy.test.model.CmsTopicComment[\"createTime\"])"
}
因为字符串 无法去解析成时间日期格式所以直接报错
如果想要接收前端时间请求日期格式,需要了解这两个注解
入参格式化@DateTimeFormat
这个注解式Spring自带的可以直接使用
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime;
重启服务,再次请求 依然是提示异常
{
"success": false,
"code": "402",
"msg": "请求参数异常",
"data": "JSON parse error: Cannot deserialize value of type `java.util.Date` from String \"2020-10-10 12:20:20\": not a valid representation (error: Failed to parse Date value '2020-10-10 12:20:20': Cannot parse date \"2020-10-10 12:20:20\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String \"2020-10-10 12:20:20\": not a valid representation (error: Failed to parse Date value '2020-10-10 12:20:20': Cannot parse date \"2020-10-10 12:20:20\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))\n at [Source: (PushbackInputStream); line: 1, column: 15] (through reference chain: com.fairy.test.model.CmsTopicComment[\"createTime\"])"
}
@JsonFormat
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") private Date createTime;注意:HH 是24小时 hh是12小时制
再次尝试
可以看到接收参数可以了,并且将时间字符串转换为日期格式,接下来看输出打印信息
2022-05-06 13:11:51.459 INFO 25640 --- [nio-8089-exec-1] c.fairy.test.controller.TopicController : 接收参数:com.fairy.test.model.CmsTopicComment@4d60cc5c
2022-05-06 13:11:51.861 INFO 25640 --- [nio-8089-exec-1] c.fairy.test.controller.TopicController : 接收日期:Sat Oct 10 12:20:20 CST 2020
2022-05-06 13:11:52.614 INFO 25640 --- [nio-8089-exec-1] c.fairy.test.controller.TopicController : 日期格式转换:2020-10-10 12:20:20
再次查看接口调用输出结果
{
"success": true,
"code": "200",
"msg": "操作成功",
"data": {
"createTime": "2020-10-10 12:20:20"
}
}
可以看到设置@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
后,可以接收时间字符串格式为yyyy-MM-dd HH:mm:ss,并会将Date日期返回结果也是输出为yyyy-MM-dd HH:mm:ss格式
使用@JsonSerialize 和 @JsonDeserialize
@JsonSerialize(using = CustomerJsonSerializer.class)//序列化 将时间日期输出格式化字符串 @JsonDeserialize(using = CustomerJsonDeserializer.class) //反序列化 接收参数 private Date createTime;
public class CustomerJsonDeserializer extends JsonDeserializer<Date> { @SneakyThrows @Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = jsonParser.getText(); return format.parse(date); } }
public class CustomerJsonSerializer extends JsonSerializer<Date> { @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss"); jsonGenerator.writeString( format.format(date)); } }
测试
{
"success": true,
"code": "200",
"msg": "操作成功",
"data": {
"createTime": "2020/10/10 12/20/20"
}
}