springmvc的日期類型轉換
阿新 • • 發佈:2019-03-25
三種 bind date this span throw exceptio 格式化 cep 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);
}
}
springmvc的日期類型轉換
# spring mvc綁定參數之類型轉換有三種方式:
## 1.實體類中加日期格式化註解
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
private Date creationTime;
## 2.屬性編輯器
spring3.1之前
在Controller類中通過@InitBinder完成
/**
* 在controller層中加入一段數據綁定代碼
* @param webDataBinder
*/
@InitBinder
public void initBinder(WebDataBinder webDataBinder) throws Exception{
simpleDateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class , new CustomDateEditor(simpleDateFormat , true));
}
備註:自定義類型轉換器必須實現PropertyEditor接口或者繼承PropertyEditorSupport類
寫一個類 extends propertyEditorSupport(implements PropertyEditor){
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
全局類型轉換
2019-03-2519:52:18
springmvc的日期類型轉換