淺談Mybatis+mysql 存儲Date類型的坑
場景:
把一個時間字符串轉成Date,存進Mysql。時間天數會比實際時間少1天,也可能是小時少了13-14小時
Mysql的時區是CST(使用語句:show VARIABLES LIKE ’%time_zone%’; 查)
先放總結:
修改方法:
1. 修改數據庫時區
2. 在jdbc.url里加后綴 &serverTimezone=GMT%2B8
3. 代碼里設置時區,給SimpleDateFormat.setTimeZone(...)
例外:new Date() 可以直接存為正確時間,其他的不行。比如我試過,把new Date用sdf轉個2次,然后就錯誤了
貼一下測試的一下渣碼
// 1.new Date()直接存數據庫則是正確的日期 結果:√ 190626,數據庫存儲正常// Date now = new Date(); // 2,new Date()用simpleDateFormat轉化為字符串再轉為Date。結果: × 少1天 190625// Date now1 = new Date();// String tempStr = yyMMddFormatter.format(now1);// String tempStrDate = tempStr.split(' ')[0];// 會加上00:00:00// Date date = yyMMddFormatter.parse(tempStrDate); // 3.配置文件加上&serverTimezone=GMT%2B8,√ 正確 // 4. 設置中國標準時區 UTC+8 結果:√// SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd'); // 設置時區: 中國標準時 China Standard Time UTC+08:00 使用GMT+8東8區,結果:?使用默認時區setTimeZone(TimeZone.getDefault);// sdf.setTimeZone(TimeZone.getTimeZone('UTC+8'));// System.out.println(sdf.getTimeZone().toString());// Date date = sdf.parse(liftMaxDt);// System.out.println(sdf.getTimeZone().toString());// System.out.println(date);//// Date targetDate = new Date(date.getTime());// System.out.println('------------------');// System.out.println(targetDate); // 5. 測試毫秒數 new Date(ms);但是要先使用sdf轉入參 結果:× 問題就在于SimpleDateFormat會混亂時區// SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');// Date date = sdf.parse(liftMaxDt);// Date targetDate = new Date(date.getTime());// System.out.println('使用sdf轉換date,在new Date(date.getTime())-----------');// System.out.println(targetDate); // 使用LocalDate.結果: × 還是少一天 DateTimeFormatter df = DateTimeFormatter.ofPattern('yyMMdd'); LocalDate ldt = LocalDate.parse(liftMaxDt, df); System.out.println('String類型的時間轉成LocalDateTime:'+ldt); // LocalDate轉LocalDateTime LocalDateTime lll = LocalDateTime.of(ldt, LocalTime.of(0,0,0)); ZoneId zone = ZoneId.systemDefault(); Instant instant = lll.atZone(zone).toInstant(); Date targetDate = Date.from(instant); // 將對象里時間屬性設置為String,數據庫里仍然用Date,用數據庫的時間函數轉化
最后,還是采用的數據庫為timestamp類型,用mysql的時間函數進行轉換,保證時間為數據庫時間
補充知識:mybatis解決java中的date類型存入oracle數據庫之后不顯示時分秒
實體類中類型為java.util.Date
private Date update_date;
數據庫中對應字段的類型為Date
不顯示 時分秒 的情況:
Mapping文件中對應字段的jdbcType為DATE類型
如果顯示時分秒的話,只需要將Mapping文件中對應字段的類型改為TIMESTAMP即可.
以上這篇淺談Mybatis+mysql 存儲Date類型的坑就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. SQL SERVER偏移函數(LAG、LEAD、FIRST_VALUE、LAST _VALUE、NTH_VALUE)2. DB2 與 Microsoft SQL Server 2000 之間的 SQL 數據復制3. 理解 DB2 中列組統計信息4. Oracle 數據字典5. 細化解析:Oracle 10g ASM 的一點經驗6. SQL Server使用CROSS APPLY與OUTER APPLY實現連接查詢7. DB2 XML 全文搜索之為文本搜索做準備8. DB2數據庫安全性全面介紹(1)9. MySQL InnoDB架構的相關總結10. Microsoft Office Access添加頁眉或頁腳的方法

網公網安備