How to get the Unix timestamp in Java

Updated onbyAlan Morel
How to get the Unix timestamp in Java

In the field of computer science, there is a concept of the unix timestamp, also known as the posix time or epoch time. This timestamp is defined as the number of seconds that have elapsed since January 1, 1970.

This is useful because it allows us to express dates and time in a single number as opposed to having to store the day, month, year, hour, minutes and seconds separately.

In this post, we'll learn all the different ways to get the unix timestamp in Java.

Instant

Java introduced a new API for date and time to replace the old Date class. This is thread-safe and immutable, among other useful improvements.

Here's how to get the current time in Java using the Instant class:

JAVA
long time = Instant.now().getEpochSecond();

You can then take this number and convert it to a date and time using the Instant class:

JAVA
long time = Instant.now().getEpochSecond(); Instant instant = Instant.ofEpochSecond(time);

With the Instant class, you can then call any method on the Instant class to get any additional piece of information that you want.

System.currentTimeMillis()

The original way to get the unix timestamp in Java was to use the System.currentTimeMillis() method. This method returns the number of milliseconds that have elapsed since the epoch time. From there you can just use simple division to get the number of seconds.

JAVA
long time = System.currentTimeMillis() / 1000;

Remember that this is only useful for when you're on Java 7 or lower, since in Java 8, you can use the much-improved Instant class.

Date

The final way to get the unix timestamp in Java is to use the Date class. This class is not thread-safe, and is not immutable, so only use it if you are on Java 7 or lower.

Here's how to use the Date class to get the unix timestamp:

JAVA
Date date = new Date(); long time = date.getTime() / 1000;

Conclusion

In this post, we explored three different ways to get the unix timestamp in Java.

Basically, if you are on a modern version of Java, you should use the Instant class, otherwise, you should use the Date class.

Hopefully, you've found this post helpful! Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.