遇到的问题,Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘releaseTime’; nested exception is org.springframework.core.convert.ConversionFailedException。
前后端分离
发生情况:前端传过来的表单数据是String类型。例如:2023-03-31 09:55:58
后端字段
@ApiModelProperty(value="发布时间")
private Date releaseTime;
关于说在字段上用 @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”),这个我用下来没法解决。
提供解决方法
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (source!=null&&source!=""){
try {
return simpleDateFormat.parse(source);
}catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
亲测有效!!!!