2017-05-23 73 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