Need to get current timestamp in Java

user717236 picture user717236 · Dec 1, 2011 · Viewed 185.7k times · Source

I need to get the current timestamp in Java, with the format of MM/DD/YYYY h:mm:ss AM/PM,

For example: 06/01/2000 10:01:50 AM

I need it to be Threadsafe as well.

Can I utilize something like this?

java.util.Date date = new java.util.Date();
System.out.println(new Timestamp(date.getTime()));

Or the examples discussed at the link here.

Answer

BalusC picture BalusC · Dec 1, 2011

The threadunsafety of SimpleDateFormat should not be an issue if you just create it inside the very same method block as you use it. In other words, you are not assigning it as static or instance variable of a class and reusing it in one or more methods which can be invoked by multiple threads. Only this way the threadunsafety of SimpleDateFormat will be exposed. You can however safely reuse the same SimpleDateFormat instance within the very same method block as it would be accessed by the current thread only.

Also, the java.sql.Timestamp class which you're using there should not be abused as it's specific to the JDBC API in order to be able to store or retrieve a TIMESTAMP/DATETIME column type in a SQL database and convert it from/to java.util.Date.

So, this should do:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 12/01/2011 4:48:16 PM