【发布时间】:2020-11-12 03:26:56
【问题描述】:
import org.springframework.format.annotation.DateTimeFormat;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date etd;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date eta;
此代码运行良好。但是我发现当时间为空字符串时会抛出异常,所以我添加了这个:
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
现在空字符串转换为null,但只使用“yyyy-MM-dd”,忽略小时和分钟。
例如eta,在我添加InitBinder之前,值是'2020-11-11 11:11:11',添加之后是'2020-11-11 00:00:00'。
如何让spring继续使用DateTimeFormat注解上的格式?
我发现了这个问题,但他似乎没有使用 DateTimeFormat :How to handle different date formats in Spring MVC controller?
【问题讨论】:
标签: java spring spring-mvc