属性 Joda LocalDate 的编辑器异常

Property Editor Exception with Joda LocalDate

我正在使用 Joda 和 Local Date。我创建了一个自定义 属性 编辑器,它从视图中接收到正确的值,例如 "23-05-2017" 但是当我尝试解析它时,我得到:

LocalDatePropertyEditor - Error Conversione DateTime
java.lang.IllegalArgumentException: Invalid format: "23-05-2017" is malformed at "-05-2017"

这是我的自定义编辑器:

public class LocalDatePropertyEditor extends PropertyEditorSupport{
    private final DateTimeFormatter formatter;

    final Logger logger = LoggerFactory.getLogger(LocalDatePropertyEditor.class);   

    public LocalDatePropertyEditor(Locale locale, MessageSource messageSource) {
        this.formatter = DateTimeFormat.forPattern( messageSource.getMessage("dateTime_pattern", new Object[]{}, locale));
    }

    public String getAsText() {
        LocalDate value = ( LocalDate ) getValue();
        return value != null ? new LocalDate( value ).toString( formatter ) : "";
    }

    public void setAsText( String text ) throws IllegalArgumentException {
        LocalDate val;
        if (!text.isEmpty()){
            try{
                val = DateTimeFormat.forPattern("dd/MM/yyyy").parseLocalDate(text);

                setValue(val);
            }catch(Exception e){

                logger.error("Errore Conversione DateTime",e);
                setValue(null);
            }
        }else{
            setValue(null);
        }
    }
}

我在控制器中注册了它:

@InitBinder
    protected void initBinder(final ServletRequestDataBinder binder, final Locale locale) {
        binder.registerCustomEditor(LocalDate.class, new LocalDatePropertyEditor(locale, messageSource));
    }

我该如何解决这个错误?

问题出在您用来解析 LocalDate 的模式中。

而不是:

val = DateTimeFormat.forPattern("dd/MM/yyyy").parseLocalDate(text);

使用这个:

val = DateTimeFormat.forPattern("dd-MM-yyyy").parseLocalDate(text);

如果您的日期格式是 23-05-2017,那么您使用了错误的格式。您应该使用 dd-MM-yyyy 而不是 dd/MM/yyyy.

我测试了一下,在controller中使用following, 如果需要,您可以更改模式 'dd-MM-yyyy'。

@InitBinder
private void dateBinder(WebDataBinder binder) {

    PropertyEditor editor = new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (!text.trim().isEmpty())
                super.setValue(LocalDate.parse(text.trim(), DateTimeFormatter.ofPattern("dd-MM-yyyy")));
        }
        @Override
        public String getAsText() {
            if (super.getValue() == null)
                return null;
            LocalDate value = (LocalDate) super.getValue();
            return value.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
        }
    };
    binder.registerCustomEditor(LocalDate.class, editor);
}