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

时间:2012-07-04 07:47:37

标签: 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));
}

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

6 个答案:

答案 0 :(得分:5)

如果只在个案中需要它,您可以在表格中注册附加到字段的自定义编辑器:

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));

答案 1 :(得分:4)

受Skipy的启发

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());

}
}

答案 2 :(得分:3)

这个怎么样?上面的内容很快就会破灭。

       public class MostLenientDateParser {
           private final List<String> supportedFormats;

           public MostLenientDateParser(List<String> supportedFormats) {
               this.supportedFormats = supportedFormats;
           }

           public Date parse(String dateValue) {
               for(String candidateFormat: supportedFormats) {
                   Date date = lenientParse(dateValue, candidateFormat);
                   if (date != null) {
                       return date;
                   }
               }
               throw new RuntimeException("tried so many formats, non matched");
           }

           private Date lenientParse(String dateCandidate, String dateFormat) {
               try {
                   return new SimpleDateFormat(dateFormat).parse(dateCandidate);
               } catch (Exception e) {
                   return null;
               }
           }
       }

也可以通过Spring Converters通过CustomDateEditor实现引用表单数据绑定。

答案 3 :(得分:2)

对于有相同问题的其他人,如果您使用的是弹簧3,您可以在模型的字段中使用真棒@DateTimeFormat(pattern =“dd-MM-yyyy”)。

只需确保使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter注册conversionService

你可以在同一个bean中拥有你想要的@DateTimeFormat。

答案 4 :(得分:1)

如果您一次只收到一种日期格式,那么您只需根据格式创建一个DateFormat实例

例如

根据输入

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

答案 5 :(得分:1)

在处理多个语言环境时,使用宽松的日期格式化程序并不是一个好主意。使用dd / MM / YYYY和MM / dd / YYYY

可以正确解析像10/11/2013这样的日期
相关问题