Get Seconds Since the Beginning of the Java Epoch



In this article, we will learn to get the seconds since the beginning of the Java epoch. To get the seconds since the beginning of epochs, you need to use Instant. The method here used is ofEpochSecond() method.

The epoch is the number of seconds that have elapsed since 00::00:00 Thursday, 1 January 1970.

Get the seconds with ChronoUnit.SECONDS ?

long seconds = Instant.ofEpochSecond(0L).until(Instant.now(), ChronoUnit.SECONDS);

Steps to retrieve seconds since Epoch

Following are the steps to retrieve seconds since Epoch ?

  • First, we will import the Instant and ChronoUnit classes from the java.time and java.time.temporal packages.
  • Create an instant for Epoch and start by using Instant.ofEpochSecond(0L) to create an Instant representing the start of the Java epoch (January 1, 1970).
  • Get the current instant and retrieve the current moment in time using Instant.now().
  • Calculate elapsed seconds using the until() method, passing Instant.now() and ChronoUnit.SECONDS, to calculate the number of seconds that have passed since the epoch.
  • Display the result by printing the calculated seconds.

Java program to retrieve seconds since Epoch

Below is the Java program to retrieve seconds since Epoch ?

import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      long seconds = Instant.ofEpochSecond(0L).until(Instant.now(), ChronoUnit.SECONDS);
      System.out.println("Seconds since the beginning of the Java epoch = "+seconds);
   }
}

Output

Seconds since the beginning of the Java epoch = 1555053202

Code Explanation

In this program, we use Java's Instant class to handle timestamps and the ChronoUnit.SECONDS to measure the elapsed time in seconds. We first create an Instant object that represents the epoch's start time (Instant.ofEpochSecond(0L)), which corresponds to January 1, 1970. Then, we call Instant.now() to get the current time. Using the until() method, we compute the difference in seconds between the epoch start and the current time. Finally, the result is printed to the console, displaying the number of seconds that have passed since the epoch began.

Updated on: 2024-10-21T17:41:50+05:30

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started