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

dav*_*ooh 4 java spring 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));
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*arc 5

灵感来自斯基皮

public class LenientDateParser extends PropertyEditorSupport {

private static final List<String> formats = new ArrayList<String>();

private String outputFormat;

static{
    formats.add("dd-MM-yyyy HH:ss");
    formats.add("dd/MM/yyyy HH:ss");
    formats.add("dd-MM-yyyy");
    formats.add("dd/MM/yyyy");
    formats.add("dd MMM yyyy");
    formats.add("MMM-yyyy HH:ss");
    formats.add("MMM-yyyy");
    formats.add("MMM yyyy");
}

public LenientDateParser(String outputFormat){
    this.outputFormat = outputFormat;
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
    if(StringUtils.isEmpty(text))
        return;
    DateTime dt = null;
    for(String format : formats){

        try{

            dt = DateTime.parse(text, DateTimeFormat.forPattern(format));

            break;

        }catch(Exception e){
            if(log.isDebugEnabled())
                log.debug(e,e);
        }
    }
    if(dt != null)
        setValue(dt.toDate());
}

@Override
public String getAsText() {
    Date date = (Date) getValue();

    if(date == null)
        return "";

    DateTimeFormatter f = DateTimeFormat.forPattern(outputFormat);

    return f.print(date.getTime());

}
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果只在puntual的情况下需要它,你可以注册附加到表单中字段的自定义编辑器:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", this.getLocale(context));
DateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss SSS", this.getLocale(context));
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateTimeFormat, true));
binder.registerCustomEditor(Date.class, "name.of.input", new CustomDateEditor(dateTimeFormat, true));
Run Code Online (Sandbox Code Playgroud)