Java get current timestamp

In this article, we will take a look at different methods to get current timestamp in java as an object of java.sql.Timestamp.

Method 1: With System.currentTimeMillis()
To get the current system time, use currentTimeMillis() method of System class. The returned value is of type long.
java.sql.Timestamp constructor takes a long value. So, we can pass the returned value of System.currentTimeMillis(). Example,

Timestamp timestamp2 = new Timestamp(System.currentTimeMillis());
System.out.println("Current timestamp is: "+timestamp2);

This prints

Current timestamp is: 2021-07-08 21:20:30.69

Method 2: From Date class
java.util.Date has a getTime() method which returns the date and time represented by the date object as a long value.
This long value can be supplied to Timestamp constructor to get the current timestamp.

To get the date object for the current date, use the no-arg Date constructor. Example,

Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
System.out.println("Current timestamp is: "+timestamp);

Method 3: Using Java 8 Instant
Java 8 introduced java.time.Instant class that represents an instant point of time. This class has a now() method which returns the current instant as an Instant object.
now() is a static method and can be invoked using the class.

Java 8 added a new static method from() to Timestamp class. It takes an object of type Instant and returns its timestamp equivalent. Example,

Instant instant = Instant.now();
Timestamp timestamp = Timestamp.from(instant);
System.out.println("Current timestamp is: "+timestamp);

Output is

Current timestamp is: 2021-07-08 22:03:53.343247

Format Timestamp
Default format of Timestamp is yyyy-MM-dd hh:mm:ss.SSS. If you want current timestamp in some other format, then use it with format() method of java.text.SimpleDateFormat as shown in the examples below.

Instant instant = Instant.now();
// get current timestamp
Timestamp timestamp = Timestamp.from(instant);
System.out.println("Current timestamp is: "+timestamp);
// format to get date
SimpleDateFormat date = new SimpleDateFormat("dd-MM-yyyy");
System.out.println("Date from timestamp :"+date.format(timestamp));
// format to get time
SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss");
System.out.println("Time from timestamp : "+time.format(timestamp));

This prints

Current timestamp is: 2021-07-09 22:07:50.475555
Date from timestamp :09-07-2021
Time from timestamp : 10:07:50

That is all on different ways to get current timestamp in java using Date(), System.currentTimeMillis() and java 8 Instant class with example programs.
Hope the article was useful.