Get Unix Timestamp in Java

In this post, we will get unix timestamp in Java.

As per wikipedia
Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

Unix time is standard way to describe point in time and used at multiple unix like operating system.

Ways to get unix timestamp in Java

There are multiple ways to get unix timestamp in Java.

Using Instant class

You can use Instant class to get unix timestamp in java in case you are using Java 8 or higher.

Output

Using System.currentTimeMillis()

You can avoid date/Instant object creation and use System.currentTimeMillis() to get current time in millisecond. You can convert milliseconds to seconds by diving it by 1000L.

Output

Using Date’s getTime() method

You can use legacy Date’s getTime() method to get unix timestamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

Output

Convert Date to unix timestamp in Java

Using Instant class

You can get Instant() from Date object using toInstant() method and get unix timestamp using getEpochSecond().

Output

You can also use LocalDate instead of java.util.Date. You need to first convert LocalDate to Instant and use getEpochSecond() to convert LocalDate to unix timestamp in Java.

Output

Using Date’s getTime() method

You can use legacy Date’s getTime() method to convert Date to unixTimeStamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

Output

That’s all about how to get Get Unix Timestamp in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *