How to Get Epoch Time in Java

In this blog post, you’ll learn how to get the current epoch timestamp in milliseconds of precision in Java. We will see different ways to get the current epoch timestamp in seconds and milliseconds of precision in Java and Java 8.

The concept of "Epoch Time" is frequently used in programming. It's especially common in scenarios where time and date need to be stored in a format that is easily sortable and comparable.

How to Get Epoch Time in Java 8

Java 8 introduced a new Date-Time API (java.time) that is comprehensive and more user-friendly, superseding the old date-time classes like java.util.Date and java.util.Calendar. We can now get the current epoch time in seconds or milliseconds using this API.
import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        // Get the current epoch time in seconds
        long epochSeconds = Instant.now().getEpochSecond();
        System.out.println("Epoch in Seconds: " + epochSeconds);

        // Get the current epoch time in milliseconds
        long epochMilliseconds = Instant.now().toEpochMilli();
        System.out.println("Epoch in Milliseconds: " + epochMilliseconds);
    }
}
Output:
Epoch in Seconds: 1690263295
Epoch in Milliseconds: 1690263295605
In the above example, Instant.now().getEpochSecond(); returns the current time in epoch seconds, and Instant.now().toEpochMilli(); returns the current time in epoch milliseconds. 

The Instant class provides two methods to get the current time:
  • getEpochSecond(): This method returns the current time in epoch seconds. It's equivalent to System.currentTimeMillis() / 1000L
  • toEpochMilli(): This method returns the current time in epoch milliseconds. It's equivalent to System.currentTimeMillis().

How to Get Epoch Time in Java (Older version)

If you are still using older versions of Java (Java 7 and older), you can get the epoch time using the java.util.Date class.

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // Get the current epoch time in milliseconds
        long epochMilliseconds = new Date().getTime();
        System.out.println("Epoch in Milliseconds: " + epochMilliseconds);
    }
}

Output:

Epoch in Milliseconds: 1690263327269
In this code snippet, new Date().getTime(); returns the current time in epoch milliseconds.

Get the Current Timestamp in Java using System.currentTimeMillis()

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // Get epoch timestamp using System.currentTimeMillis()
        long currentTimestamp = System.currentTimeMillis();
        System.out.println("Current epoch timestamp in millis: " + currentTimestamp);
    }
}

Output:

Current epoch timestamp in millis: 1690263404149

Conclusion

In this blog post, we discussed different ways to get the current epoch timestamp in seconds and milliseconds of precision using Java and Java 8 API.

Comments