@DateTimeFormat踩坑日记

1,357 阅读1分钟

引用blog.csdn.net/A1962747112… springboot版本:2.2.1.RELEASE

今天用@DateTimeFormat来标注在对象的字段里面,发现无法将前端的参数成功转化为日期,查了很久,后来发现是一个小问题导致的。

注意 LocalDateTime不能使用 pattern = "yyyy-MM-dd"

否则报错:

Field error in object 'userParam' on field 'endTime': rejected value [2020-06-18]; codes [typeMismatch.userParam.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userParam.endTime,endTime]; arguments []; default message [endTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'endTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2020-06-18'; nested exception is java.time.format.DateTimeParseException: Text '2020-06-18' could not be parsed at index 10]

错误用法:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDateTime endTime;

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime endTime;

正确用法:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate endTime;

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate endTime;