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 ne
You can make use of java.util.Date
with direct date string format:
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
I did it like this when I wanted a tmiestamp
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
Hope it helps :) As a newbie I think it's self-explanatory
I think you also need import java.text.SimpleDateFormat; header for it to work :))
Try this single line solution :
import java.util.Date;
String timestamp =
new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date());
Here is the same kind of code but using the third-party library Joda-Time 2.3.
In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.
org.joda.time.DateTime now = new DateTime();
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
String nowAsString = formatter.print( now );
System.out.println( "nowAsString: " + nowAsString );
When run…
nowAsString: 11/28/2013 11:28:15 PM