使用Spring MVC设置输入文本的日期格式
问题内容:
如何Date
使用Spring
MVC在文本字段中设置的格式?
我正在使用Spring Form标签库和input
标签。
我现在得到的是这样的东西Mon May 28 11:09:28 CEST 2012
。
我想以dd/MM/yyyy
格式显示日期。
问题答案:
在yr控制器中注册日期编辑器:
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
}
然后数据编辑器本身可以如下所示:
public class LocalDateEditor extends PropertyEditorSupport{
@Override
public void setAsText(String text) throws IllegalArgumentException{
setValue(Joda.getLocalDateFromddMMMyyyy(text));
}
@Override
public String getAsText() throws IllegalArgumentException {
return Joda.getStringFromLocalDate((LocalDate) getValue());
}
}
我使用我自己的抽象实用程序类(Joda)解析日期,实际上是Joda Datetime库中的 LocalDates-
推荐使用,因为标准的Java日期/日历是可恶的imho。但是你应该明白这个想法。另外,您可以注册一个全局编辑器,因此您不必在每个控制器上都这样做(我不记得怎么做)。