2014-05-16 121 views
0

我希望生成格式为yyyy-MM-dd HH:mm:ss的当前时间戳。我写了下面的代码,但它总是给我这种格式yyyy-MM-dd HH:mm:ss.xJava中的格式化时间戳

你如何摆脱.x部分?

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
String currentTime = df.format(new Date()); 
Timestamp timestamp = Timestamp.valueOf(currentTime); 

我需要一个时间戳类型写入MySQL。

回答

2

可能您正在查看String表示,Timestamp对象通过使用System.out.println或其他方法在控制台中打印数据库引擎或其Java表示,请注意,实际存储的数据(在Java方面或在您的数据库引擎中)是一个代表自纪元以来的时间(通常为1970年1月1日)以及您想要/需要存储的日期的数字。

不应讲究String格式是当你消耗Timestamp表示。这可以如果你申请同一SimpleDateFormat让你timestamp对象的String表示很容易地以实例阐述:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
String currentTime = df.format(new Date()); 
Timestamp timestamp = Timestamp.valueOf(currentTime) 
//will print without showing the .x part 
String currentTimeFromTimestamp = df.format(currentTime); 

无论如何,如果你想在当前时间,就直接从new Date结果创建Timestamp

Timestamp timestamp = new Timestamp(new Date().getTime()); 
1

您可以将时间戳作为字符串插入到MySQL表中。 currentTime中的字符串表示就足够了。

0

写时间戳的最佳方式或Java中的任何数据类型是使用PreparedStatement和适当的方法

PreparedStatement ps = conn.prepareStatement("update t1 set c1=?"); 
    ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime())); 
    ps.executeUpdate(); 
+0

你能详细点吗?谢谢 – TonyGW