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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11324622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:39:59  来源:igfitidea点击:

How to handle different date formats in Spring MVC controller?

javaspringspring-mvc

提问by davioooh

Is it possible to handle different date format in a Spring MVC controller?

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

I know that setting something like this

我知道设置这样的东西

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

I can handle dd/MM/yyyyformat, but what if i want to parse also dates in yyyyMMddhhmmssformat? Should I add multiple CustomDateEditors in my controller?

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

采纳答案by Jigar Joshi

If at a time you receive only one format of date, then you could simply create one instance of DateFormatbased on format

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

for example

例如

Decide the format based on the input

根据输入决定格式

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

回答by Thiamath

If you need it only at puntual cases, you can register the custom editor attached to a field in the form:

如果您只在 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));

回答by Marc

Inspired by Skipy

灵感来自 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());

}
}

回答by skipy

How about this. the above can go out of whack pretty soon.

这个怎么样。上述情况很快就会失控。

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

This could also be referenced through Spring Converters via a CustomDateEditor implementation for form-data binding.

这也可以通过 Spring 转换器通过用于表单数据绑定的 CustomDateEditor 实现来引用。

回答by redochka

For others having the same question, if you are using spring 3 You can use the awesome @DateTimeFormat(pattern="dd-MM-yyyy") in the field of your model.

对于其他有同样问题的人,如果您使用的是 spring 3,您可以在模型字段中使用很棒的 @DateTimeFormat(pattern="dd-MM-yyyy") 。

Just make sure to register a conversionService with your org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

只需确保使用您的 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter 注册一个 ConversionService

You can have as much as you want of @DateTimeFormat in the same bean.

您可以在同一个 bean 中拥有任意数量的 @DateTimeFormat。

回答by Ashutosh

Not a great idea to have lenient date formatters when dealing with multiple locales. A date like 10/11/2013 will get parsed correctly with both dd/MM/YYYY and MM/dd/YYYY

在处理多个语言环境时使用宽松的日期格式化程序并不是一个好主意。像 10/11/2013 这样的日期将被正确解析为 dd/MM/YYYY 和 MM/dd/YYYY