Formatting timestamp in Java

2019-01-29 07:44发布

问题:

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.

回答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.

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());


回答2:

You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.



回答3:

The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method

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