项目中遇到的LocalDateTime时间格式转换问题
最近在重构项目时,把java.util.Date类型改成了java.time.LocalDateTime,但是遇到一点小问题,在这里分享一下。
后端代码:
@Data
public class RoleChengwei {
@Id
private String id;
/**
* 是否在使用
*/
private Integer state;
/**
* 角色id
*/
private String roleId;
/**
* 称谓id
*/
private Integer chengweiId;
/**
* 装饰过期时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDateTime endTime;
}
前端代码:
$("#end_time").datebox({
width: 160,
showSeconds: true,
required: true
});
前端界面截图如下

前端使用的是easyui框架,datebox就是日期框(只包含年月日的日期),在数据传到后端时,发生类型转换错误
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'roleChengwei' on field 'endTime': rejected value [2022-08-28]; codes [typeMismatch.roleChengwei.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [roleChengwei.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 [@com.fasterxml.jackson.annotation.JsonFormat @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2022-08-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-08-28]]
当看到这个报错信息的时候,其实就是时间格式不兼容,想着java.time包下应该有日期类型,果然,LocalDate就是java.time包下的,把以上实体类endTime属性的类型改成LocalDate,问题解决。
@Data
public class RoleChengwei {
@Id
private String id;
/**
* 是否在使用
*/
private Integer state;
/**
* 角色id
*/
private String roleId;
/**
* 称谓id
*/
private Integer chengweiId;
/**
* 装饰过期时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate endTime;
}