Formatting timestamp in Java

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

Leave a Comment