How to get the Unix timestamp in Java

The Unix timestamp is an integer value representing the number of seconds elapsed since the Unix Epoch on January 1st, 1970, at 00:00:00 UTC. In short, a Unix timestamp is the number of seconds between a specific date and the Unix Epoch.

There are multiple ways to compute a Unix timestamp in Java.

The simplest way to get a Unix atimestamp is using the Instant class. The Instant class is part of new date and time API and provides several methods to work with timestamps.

long unixTime = Instant.now().getEpochSecond();

System.out.println(unixTime);
// 1665083712

The getEpochSecond() method returns the seconds from the Unix epoch of 1970-01-01T00:00:00Z.

To convert a Unix timestamp back to an instance of Instant, use the Instant.ofEpochSecond() method:

long unixTime = 1665083712;
Instant instant = Instant.ofEpochSecond(unixTime);

System.out.println(instant);
// 2022-10-06T19:15:12Z

An Instant object represents an unique moment in the timeline using a universal timezone (UTC).

In Java 7 and below, you can use the System.currentTimeMillis() method to get the current time in milliseconds.

Later, you can convert the milliseconds into seconds to get the Unix timestamp, as shown below:

long unixTime = System.currentTimeMillis() / 1000L;

System.out.println(unixTime);
// 1665083712

Finally, the last method to get the Unix timestamp in Java is using the legacy Date class:

Date date = new Date();
long unixTime = date.getTime() / 1000L;

System.out.println(unixTime);
// 1665083712

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.