Java 8 – How to convert Instant to number of Seconds and vice-versa ?

In this article, we will learn how to convert Instant to number of Seconds and vice-versa using getEpochSecond() and ofEpochSecond() methods of Instant respectively provided in Java 1.8 version

Conversion of Instant to Second & vice-versa :

There are 2 methods available in an Instant for conversion of Instant to Second and vice-versa,

  • getEpochSecond() – gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z
  • ofEpochSecond(epochSecond) – gets an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z

1. Convert Instant to Seconds :

  • getEpochSecond() – Converts an Instant to number of Seconds from 1970-01-01T00:00:00Z in long type

ConvertInstantToSeconds.java

package in.bench.resources.java8.instant.examples;

import java.time.Instant;

public class ConvertInstantToSeconds {

	public static void main(String[] args) {

		// 1. get current Date/time or Instant at UTC
		Instant instant = Instant.now();
		System.out.println("Current Instant at UTC/GMT is :- \n" 
				+ instant);


		// 2. get Seconds from an Instant
		long seconds = instant.getEpochSecond();
		System.out.print("\nInstant to number of Seconds in long format :- \n" 
				+ seconds);
	}
}

Output:

Current Instant at UTC/GMT is :- 
2022-08-19T17:45:41.572316200Z

Instant to number of Seconds in long format :- 
1660931141

2. Convert Seconds to Instant :

  • ofEpochSecond(long) – This method obtains an instance of Instant from a seconds value provided as argument in long type

ConvertSecondsToInstant.java

package in.bench.resources.java8.instant.examples;

import java.time.Instant;

public class ConvertSecondsToInstant {

	public static void main(String[] args) {

		// 1. seconds in long format
		long seconds = 1660820905L;
		System.out.println("Number of Seconds in long format :- \n" 
				+ seconds);


		// 2. convert seconds to an Instant
		Instant instant = Instant.ofEpochSecond(seconds);
		System.out.print("\nSeconds to an Instant is :- \n" 
				+ instant);
	}
}

Output:

Number of Seconds in long format :- 
1660820905

Seconds to an Instant is :- 
2022-08-18T11:08:25Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert Instant to number of Milliseconds and vice-versa ?
Java 8 – How to convert Instant to an OffsetDateTime ?