使用Joda LocalDate的属性编辑器异常

问题描述 投票:2回答:3

我正在使用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));
    }

我该如何解决这个错误?

java spring spring-mvc editor jodatime
3个回答
0
投票

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

代替:

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

用这个:

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

1
投票

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


0
投票

我测试了它,只需在控制器中使用以下,你可以改变模式'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);
}
© www.soinside.com 2019 - 2024. All rights reserved.