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.
The threadunsafety of
SimpleDateFormatshould 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 ofSimpleDateFormatwill be exposed. You can however safely reuse the sameSimpleDateFormatinstance within the very same method block as it would be accessed by the current thread only.Also, the
java.sql.Timestampclass 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 aTIMESTAMP/DATETIMEcolumn type in a SQL database and convert it from/tojava.util.Date.So, this should do: