java - Joda LocalDate 的属性编辑器异常

标签 java spring spring-mvc editor jodatime

我正在使用 Joda 和 Local Date。我创建了一个自定义属性编辑器,它从 View 中接收到正确的值,例如 "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);
        }
    }
}

在 Controller 内部我注册了它:

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

我该如何修复这个错误?

最佳答案

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

关于java - Joda LocalDate 的属性编辑器异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138458/

相关文章:

java - Spring 启动 : How to use multiple schemas and dynamically choose which one to use for every request at runtime

Spring Maven 存储库问题

java - Spring Test 的 MockMvc 和 Spring Remoting 的 HttpInvoker

java - Spring 中的 Maven 配置文件和应用程序 yml 文件

java - 使用状态来管理 onTouchEvent

java - 在 JPA 中, native 查询是否发生回滚?

java - 如何判断哪些 spring-boot 自动配置器已被激活?

java - 使用映射的 JPA 集合

java - 使用 spring : Unresolved forward references Jackson Exception 反序列化 JSON

spring - 如何使用 JSTL 获取 jsp 中列表的元素?