在Java中格式化时间戳 [英] Formatting timestamp in Java
问题描述
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.valueOf(currentTime);
我需要用于写入mysql的时间戳类型。
可能您正在查看 String
表示, Timestamp
对象通过在控制台中使用 System.out.println
或其他方法。请注意,实际存储的数据(在Java端或数据库引擎中)是一个代表自1970年代以来(通常是1970年1月1日)以及您想要/需要存储的日期的数字。
您不应注意您消费时所表示的字符串
格式时间戳
。如果您应用相同的 SimpleDateFormat
来获取的
object: 字符串
表示形式, timestamp
DateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm: SS);
String currentTime = df.format(new Date());
时间戳timestamp = Timestamp.valueOf(currentTime)
//将打印,不显示.x部分
字符串currentTimeFromTimestamp = df.format(currentTime);
无论如何,如果您想要当前时间,只需创建 Timestamp
new Date
:
Timestamp timestamp = new Timestamp(new Date()。getTime());
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
How do you get rid of the .x
part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.
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.
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);
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());
这篇关于在Java中格式化时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!