Java获取系统时间日期存储到数据库Timestamp时间限制

版权声明:任何形式的转载请注明出处 https://blog.csdn.net/weixin_42259823/article/details/85955951

由于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获取数据并向数据库中存储。

http://chencheng.vip/csdn/

猜你喜欢

转载自blog.csdn.net/weixin_42259823/article/details/85955951