springmvc自定义日期编辑器

时间:2023-02-05 19:34:49

1.控制器

@Controller
public class MyController { // 处理器方法
@RequestMapping(value = "/first.do")
public String doFirst(Date birthday, int age) {
return "/jsp/two.jsp";
} // 自定义一个方法
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new MyDateEdit());
}
}

2.自定义日期编辑器

public class MyDateEdit extends PropertiesEditor {

    @Override
public void setAsText(String source) throws IllegalArgumentException {
SimpleDateFormat sdf = getDateFromte(source);
try {
Date date = sdf.parse(source);
setValue(date);
} catch (ParseException e) {
e.printStackTrace();
}
} private SimpleDateFormat getDateFromte(String source) { SimpleDateFormat sdf = new SimpleDateFormat(); if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) {
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) {
sdf = new SimpleDateFormat("yyyy/MM/dd");
}
if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) {
sdf = new SimpleDateFormat("yyyyMMdd");
}
if (Pattern.matches("^\\d{4}年\\d{2}月\\d{2}日$", source)) {
sdf = new SimpleDateFormat("yyyy年MM月dd日");
}
return sdf;
} }