在 Java 中格式化时间戳

2022-01-13 00:00:00 format timestamp java

我希望生成 yyyy-MM-dd HH:mm:ss 格式的当前时间戳.我编写了以下代码,但它总是给我这种格式 yyyy-MM-dd HH:mm:ss.x

I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format 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.

I need to have a timestamp type for writing into mysql.

推荐答案

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

Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.

您不应该在使用您的Timestamp时注意它所代表的String格式.如果您应用相同的 SimpleDateFormat 来获得 timestamp 对象的 String 表示,则可以很容易地证明这一点:

You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:

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 即可:

Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:

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

相关文章