一、修改Spring Boot配置文件
spring:
mvc:
format:
date: yyyy-MM-dd #日期格式
二、使用注解@DateTimeFormat
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
三、编写工具类
此工具类可对多格式进行处理:
package util;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MultiFormatDateEditor extends PropertyEditorSupport {
@Override
//setAsText()通常是是将String变成你想要的类型,然后给Bean赋值,这里我们可以对{text}进行处理然后返回出去
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
//判断数据是否为null或者''
if (StringUtils.hasText(text)) {
date = format.parse(text);
}
} catch (ParseException e) {
format = new SimpleDateFormat("yyyy/MM/dd");
try {
date = format.parse(text);
} catch (ParseException parseException) {
parseException.printStackTrace();
}
}
setValue(date);
}
}
然后在initBinder 方法里直接引用
@InitBinder 用于在@Controller中标注于方法上,表示为当前控制器注册一个属性编辑器,只对当前的Controller 有效。 @InitBinder 标注的方法必须有一个参数 WebDataBinder。所谓的属性编辑器可以理解就是帮助我们完成参数绑定。
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new MultiFormatDateEditor());
}