Java獲取系統時間日期儲存到資料庫Timestamp時間限制
阿新 • • 發佈:2019-01-07
由於Java中沒有datetime資料型別,timestamp型別資料在資料庫中只能儲存到2038年,資料庫中存完整的時間日期可以使用datetime。本文主要探索在Java中使用Timestamp型別時間插入到資料庫欄位型別為datetime的可行性。關於Java中util和sql時間日期的資料的轉換可以參考:https://blog.csdn.net/weixin_42259823/article/details/85945227
操作環境:jdk1.8、mysql5.7.23
初始化資料,將資料庫Timestamp型別資料取值範圍外的資料寫入資料庫
String strDate="2050年01月07日 08:09:10"; java.util.Date date = null; SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); try { date = simpleDateFormat.parse(strDate); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); }
資料庫欄位資料型別為timestamp
//時間轉為java.sql.Timestamp型別,Java中使用Timestamp java.sql.Timestamp ctime = new java.sql.Timestamp(date.getTime()); pstmt.setTimestamp(1, ctime); //向資料庫寫入時間 //報錯:Data truncation: Incorrect datetime value: '2050-01-07 08:09:10' for column 'haha' at row 1 //Java中使用Date java.sql.Date ctime = new java.sql.Date(date.getTime()); pstmt.setDate(1, ctime); //報錯:Data truncation: Incorrect datetime value: '2050-01-07' for column 'haha' at row 1
資料庫欄位資料型別為datetime
//Java中使用java.sql.Date Date ctime = new java.sql.Date(date.getTime()); pstmt.setDate(1, ctime); //資料庫中存入:2050-01-07 00:00:00 //Java中使用java.sql.Timestamp Timestamp ctime = new java.sql.Timestamp(date.getTime()); pstmt.setTimestamp(1, ctime); //資料庫中存入:2050-01-07 08:09:10
結論:可以在資料庫中使用datetime資料型別,Java中使用Timestamp獲取資料並向資料庫中儲存。