1. 程式人生 > 程式設計 >淺談Mybatis+mysql 儲存Date型別的坑

淺談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));
  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型別的坑就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。