Java Current Timestamp Sample Code

Java has a couple of solutions for getting the current timestamp. The Timestamp class and the SimeDateFormat along with Date have methods to get the current timestamp.


Timestamp Class

Start off by calling the System to get current time in milliseconds. Create a new Timestamp object and pass in the current milliseconds. You can then print the current time in the format [year-month-day hour:minute:seconds].

//Get the current time in milliseconds
long milliseconds = System.currentTimeMillis();
		
//Create Timstamp instance and pass milliseconds
Timestamp timestamp = new Timestamp(milliseconds);
		
System.out.println("Timestamp: "+timestamp);
Timestamp: 2018-01-28 05:46:23.885


SimpleDateFormat Class

You have more flexibility with the SimpleDateFormat in how you format the output of the current time. Define the format you want when creating an instance of SimeDateFormat. Calling the format() method and passing in a Date object will result in the current time.

//Create SimpleDateFormat Object and set the time format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		
//Create Date object
Date date = new Date();
		
//Format simpledateformat return String
String strTimestamp = simpleDateFormat.format(date);
		
System.out.println("Timestamp: "+strTimestamp);
Timestamp: 2018/01/28 05:58:25


SimpleDateFormat Current Date

Format current date using SimpleDateFormat to use the abbreviated month name.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM d y");
Timestamp: Jan 28 2018


SimpleDateFormat Current Date

Format current date using SimpleDateFormat to use the full month name.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM d y");
Timestamp: January 28 2018


SimpleDateFormat Current Time

Format the current time and date with two digit month, two digit day, four digit year following by hour minute and seconds.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Timestamp: 01/28/2018 06:18:21


SimpleDateFormat Current Time Zone

You can also include the timezone to the previous format above.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss zzzz");
Timestamp: 01/28/2018 06:20:40 Eastern Standard Time


SimpleDateFormat Current Time AM PM

You can also include an AM or PM identifier in the current timestamp.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a zzzz");
Timestamp: 01/28/2018 06:22:13 AM Eastern Standard Time


Concluding Comments

The Java programming language provides at least two good solutions for getting the current timestamp. I prefer using the SimpleDateFormat with Date because it offers the most amount of flexibility in how I display the current time.



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *