項目結構:
一、數據庫中time的字段為datetime
1. 數據庫設計如圖
2. addNews.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="ctx" value="${pageContext.request.contextPath}"/> <script language="javascript" type="text/javascript" src="${ctx }/js/My97DatePicker/WdatePicker.js"></script> <table> <tr> <td align="right">時間:</td> <td> <input cssClass="Wdate" onfocus="WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd HH:mm:ss'});" name="newsTime" size="40" value="" /> </td> </tr> </table> <!--添加其他字段的代碼省略-->
插入時間所使用的控件:My97DatePicker http://www.my97.net/index.asp ,也可以這里下載
3. News.java
import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; //新聞 public class News implements Serializable{ private Integer newsID; private String newsTitle; private String newsAbstract; private String newsAuthor; /** * 使用@ModelAttribute接收參數時 * form表單中有日期,Spring不知道該如何轉換, * 要在實體類的日期屬性上加@DateTimeFormat(pattern="yyyy-MM-dd")注解 * 使用@DateTimeFormat格式:這樣jsp頁面傳遞過來的String類型的時間 '2018-04-12 19:40:17' 轉換為 Date 類型 */ @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date newsTime;//新聞時間 private String newsContent; public News(){ super(); } //setter and getter }
4. NewsMapper.java和NewDynaSqlProvider.java
(1)NewsMapper.java
//動態插入新聞 @SelectProvider(type=NewsDynaSqlProvider.class,method="insertNews") void save(News news);
(2)NewDynaSqlProvider.java
//動態插入 public String insertNews(final News news){ return new SQL(){ { INSERT_INTO("news"); if(news.getNewsTitle() != null && !news.getNewsTitle().equals("")){ VALUES("newsTitle", "#{newsTitle}"); } if(news.getNewsAbstract() != null && !news.getNewsAbstract().equals("")){ VALUES("newsAbstract", "#{newsAbstract}"); } if(news.getNewsAuthor() != null && !news.getNewsAuthor().equals("")){ VALUES("newsAuthor", "#{newsAuthor}"); } if(news.getNewsTime() != null && !news.getNewsTime().equals("")){ VALUES("newsTime", "#{newsTime}"); } if(news.getNewsContent() != null && !news.getNewsContent().equals("")){ VALUES("newsContent", "#{newsContent}"); } } }.toString(); }
5. testService.java和testServiceImpl.java
(1)testService.java
/** * 添加新聞 * @param News 新聞對象 */ void addNews(News news);
(2)testServiceImpl.java
@Override public void addNews(News news) { newsMapper.save(news); }
6. NewsController.java
@RequestMapping(value="/addNewst") public ModelAndView addNewst( String flag, @ModelAttribute News news, ModelAndView mv, HttpSession session){ if(flag.equals("1")){ mv.setViewName("addNews"); }else{ testService.addNews(news); mv.setViewName("redirect:/htNews"); } return mv; }
插入時間除了在News.java中使用@DateTimeFormat設置一下時間格式,在插入語句中跟插入String類型的字段沒有區別。
運行界面:
7. 查詢語句
//查詢所有新聞(包括查詢時間) @Select("select * from news") List<News> findAllNews();
8. 查詢頁面獲取時間時,也要設置時間格式:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="f" %> <!--省略其他代碼--> <p> <f:formatDate value="${news.newsTime }" type="both" dateStyle="long"/> </p> <!--省略其他代碼-->
<fmt:formatDate> 標簽設置時間格式的屬性參考:http://www.runoob.com/jsp/jstl-format-formatdate-tag.html
運行界面:
另外發現在插入時間2018-04-11 15:54:26時,后台獲取的時間並不是2018-04-11 15:54:26的格式,而是Wed Apr 11 15:54:26 CST 2018
News [newsID = null newsTitle = 新聞標題 newsAbstract = abstract newsTime = Wed Apr 11 15:54:26 CST 2018 newsContent = add time] date type: class java.util.Date newsTime: Wed Apr 11 15:54:26 CST 2018
傳入的數據時間格式:
二、數據庫中time的字段為timestamp
1. 數據庫中字段屬性為timestamp時,可設置自動更新時間
設置方法:
(1)用創建數據庫時設置
CREATE TABLE `notices` ( `noticeID` int(50) NOT NULL AUTO_INCREMENT, `noticeName` varchar(100), `noticeContent` varchar(500), `noticeTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`noticeID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
如果希望在更新記錄時還能自動更新noticeTime字段為當前時間:
`noticeTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
(2)在Navicat for MySQL中設置
2. Notices.java
import java.io.Serializable; import java.util.Date; public class Notices implements Serializable{ private Integer noticeID; private String noticeName; private String noticeContent; private Date noticeTime; public Notices(){ super(); } //setter and getter }
3. SQL動態插入,在插入內容時,會自動獲取當前時間並保存進數據庫
//動態插入公告 public String insertNotice(final Notices notices){ return new SQL(){ { INSERT_INTO("notices"); if(notices.getNoticeName() != null && !notices.getNoticeName().equals("")){ VALUES("noticeName", "#{noticeName}"); } if(notices.getNoticeContent() != null && !notices.getNoticeContent().equals("")){ VALUES("noticeContent", "#{noticeContent}"); } } }.toString(); }
三、MySQL中timestamp和datetime的區別
|
|
timestamp |
datetime |
同 |
默認格式 |
yyyy-MM-dd HH:mm:ss |
|
異 |
時間范圍 |
'1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC 即1970——2038年 |
'1000-01-01 00:00:00' to '9999-12-31 23:59:59' 即1001——9999年 |
時區 |
自動時區轉化 |
不支持時區 |
|
存儲 |
4字節(空間利用率更高) |
8字節 |
|
默認值 |
如果不設置的話,默認值也是null |
null |