The UNIX timestamp (also known as POSIX time or EPOCH time) is a way to compute time as a running total of seconds that have elapsed since Thursday, 1 January 1970, 00:00:00 Coordinated Universal Time (UTC), minus the number of leap seconds that have elapsed since then.

Unix time is widely used in Unix-like operating systems file formats. There are multiple ways to compute Unix timestamp in Java.

Using Instant Class

In Java 8 and higher, you can use the Instant class from new date and time API to get the UNIX timestamp as shown below:

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

To convert a Unix timestamp back to an instance of Instant, you can do the following:

long unixTime = 1577094336;
Instant instant = Instant.ofEpochSecond(unixTime);
// 2019-12-23T09:45:36Z

Using System.currentTimeMillis() Method

In Java 7 and below, you can use the System.currentTimeMillis() method to get the current time in milliseconds. Then you can convert the milliseconds into seconds to get the Unix timestamp as shown below:

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

Using Date Class

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

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

Further Reading

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

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.