Java中的时间戳格式化

Java中的时间戳格式化,java,format,timestamp,Java,Format,Timestamp,我希望以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); 我需要有

我希望以
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

您可能正在查看
时间戳对象在数据库引擎中给出的
字符串
表示,或者通过在控制台中使用
System.out.println
或通过其他方法打印它的Java表示。请注意,真正存储的(在Java端或数据库引擎中)是一个数字,它表示自纪元以来的时间(通常是1970年1月1日)和您想要/需要存储的日期

您不应注意使用
时间戳时所表示的
字符串
格式。如果应用相同的
SimpleDateFormat
来获取
时间戳对象的
字符串
表示形式,则可以很容易地演示这一点:

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);
无论如何,如果您想要当前时间,只需直接从
新日期的结果创建
时间戳

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

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

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

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