我正在使用 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/