springmvc的日期類型轉換web
# spring mvc綁定參數之類型轉換有三種方式:spring
## 1.實體類中加日期格式化註解mvc
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
private Date creationTime;編輯器
## 2.屬性編輯器this
spring3.1以前spa
在Controller類中經過@InitBinder完成orm
/**
* 在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);
}
}繼承
## 3. 類型轉換器Converter接口
全局類型轉換get
2019-03-2519:52:18