How to get current timestamp in Java

To get the current timestamp in Java:

  1. Use the Instant class from Java 8 new date and time API.
  2. The Instant.now() static method returns an object representing a specific moment in the timeline in UTC.
Instant now = Instant.now();

System.out.println(now);
// 2022-10-06T18:45:00.282494Z

An Instant is a unique point in the timeline and is mainly used to represent timestamps in Java 8 and higher. You can use this class to get the current moment from the system clock.

Alternatively, you can also convert an instance of java.sql.Timestamp to Instant as shown below:

Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Instant now = timestamp.toInstant();

System.out.println(now);
// 2022-10-06T19:00:03.584Z

Another way to create an Instant object is using the java.util.Date class:

Date date = new Date();
Instant now = date.toInstant();

System.out.println(now);
// 2022-10-06T19:00:03.584Z

Note: To get a Unix timestamp (seconds from the epoch of 1970-01-01T00:00:00Z) in Java, use the Instant.now().getEpochSecond() method.

In Java 7 and below, you need to use the java.sql.Timestamp class to get the current timestamp:

// Use System.currentTimeMillis()
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 2022-10-07 00:04:05.771

// Convert Date to Timestamp
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());

You may be interested in reading the following Java date and time tutorials:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.