将 Java 日期转换为 Sql 时间戳

2022-08-31 20:16:14

我试图在将其转换为java.sql.Timestamp后插入,并且我正在使用以下代码段:java.util.Date

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());

但这给了我sq2014-04-04 13:30:17.533

有没有办法在没有毫秒的情况下获得输出?


答案 1

您可以使用以下命令切断毫秒:Calendar

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

输出:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

答案 2

看看:SimpleDateFormat

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());  

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));