一.局部方式
在對應的實體類上寫上@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")註解,後面的格式需要按照要求來
二.全局方式
實現Converter接口
public class StringToDateConverter implements Converter<String, Date> {
/**
* 用於把 String 類型轉成日期類型
*/
@Override
public Date convert(String source) {
DateFormat format = null;
try {
if(StringUtils.isEmpty(source)) {
throw new NullPointerException("請輸入要轉換的日期");
}
format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(source);
return date;
} catch (Exception e) {
throw new RuntimeException("輸入日期有誤");
}
}
}
在 spring 配置文件中配置類型轉換器。
<!-- 配置類型轉換器工廠 -->
<bean id="converterService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 給工廠注入一個新的類型轉換器 -->
<property name="converters">
<array>
<!-- 配置自定義類型轉換器 -->
<bean class="com.gaipian.web.converter.StringToDateConverter"></bean>
</array>
</property>
</bean>
在 annotation-driven 標籤中引用配置的類型轉換服務
<!-- 引用自定義類型轉換器 -->
<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>
三.屬性編輯器(spring3.1之前)
在Controller類中通過@InitBinder完成
/**
* 在controller層中加入一段數據綁定代碼
* @param webDataBinder
*/
@InitBinder
public void initBinder(WebDataBinder webDataBinder) throws Exception{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
simpleDateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
}
備註:自定義類型轉換器必須實現PropertyEditor接口或者繼承PropertyEditorSupport類
寫一個類 extends propertyEditorSupport(implements PropertyEditor){
public void setAsText(String text){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy -MM-dd hh:mm");
Date date = simpleDateFormat.parse(text);
this.setValue(date);
}
public String getAsTest(){
Date date = (Date)this.getValue();
return this.dateFormat.format(date);
}
}