如何在Spring MVC控制器中处理不同的日期格式?


问题内容

Spring MVC控制器中可以处理不同的日期格式吗?

我知道像这样设置

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, false));
}

我可以处理dd/MM/yyyy格式,但是如果我还要解析yyyyMMddhhmmss格式的日期怎么办?我应该CustomDateEditor在控制器中添加多个s吗?


问题答案:

如果一次只收到一种格式的日期,则可以简单地DateFormat基于格式创建一个实例。

例如

根据输入确定格式

DateFormat df = null;
if(recievedDate.indexOf("//")!=-1){
    df = new SimpleDateFormat("dd/MM/yyyy")
}else{
    df = new SimpleDateFormat("yyyyMMddhhmmss")
}