2017-05-23 32 views
2

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

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

我该如何解决这个错误?

回答

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