方法一:實體類中加日期格式化注解
- @DateTimeFormat(pattern = "yyyy-MM-dd")
- private Date receiveAppTime;
如上,在對應的屬性上,加上指定日期格式的注解, ,輕松解決問題!
方法二:控制器Action中加入一段資料綁定代碼
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //true:允許輸入空值,false:不能為空值
}
下面的可以同時日期和時間
// 自定義類型轉換器
@InitBinder
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("YYYY-MM-DD hh:mm:ss"), true));
}
方法四:适合頁面把日期類型轉換成字元串且JSP,Freemark頁面
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:formatDate value="${job.jobtime }" pattern="yyyy-MM-dd HH:mm:ss"/>
比對時間最詳細的還是這個:yyyy-MM-dd HH:mm:ss
出來的結果就是類似:2019-07-07 18:34:01