我希望生成yyyy-MM-dd HH:mm:ss格式的当前时间戳。我已经编写了以下代码,但它总是给出这种格式的yyyy-MM-dd HH:mm:ss.x
如何摆脱.x部件?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);我需要有一个写入mysql的时间戳类型。
发布于 2014-05-16 11:26:39
您可能正在查看Timestamp对象在数据库引擎中提供的String表示,或者通过在控制台中使用System.out.println或其他方法打印它。请注意,真正存储(在Java端或数据库引擎中)的是一个数字,它表示自纪元以来的时间(通常是1970年1月1日)和您想要/需要存储的日期。
当你使用你的时,你不应该注意它所代表的String格式。如果应用相同的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());发布于 2014-05-16 11:34:44
您可以将时间戳作为字符串插入到MySQL表中。您在currentTime中的字符串表示就足够了。
发布于 2014-05-16 11:53:26
在Java语言中编写时间戳或任何数据类型的最佳方法是使用PreparedStatement和适当的方法
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();https://stackoverflow.com/questions/23692117
复制相似问题