Java 8 – How to get Seconds and Nanoseconds from an Instant ?

In this article, we will learn how to get Seconds & Nanoseconds from an Instant using getEpochSecond() & getNano() methods provided in Java 1.8 version

Get Seconds/Nanos from an Instant :

  • There are 2 methods available to get Seconds/Nanos from an Instant
    1. getEpochSecond() – gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z
    2. getNano() – gets the number of nanoseconds, later along the time-line, from the start of the second
  • Lets see an example to get Seconds & Nanoseconds from an Instant

GetSecondAndNanoSecondFromAnInstant.java

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

import java.time.Instant;

public class GetSecondAndNanoSecondFromAnInstant {

	public static void main(String[] args) {

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


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


		// 2. get Nanoseconds from an Instant
		int nanoseconds = instant.getNano();
		System.out.print("\nFractional Nanoseconds part from an Instant in integer format :- \n" 
				+ nanoseconds);
	}
}

Output:

Current Instant at UTC/GMT is :- 
2022-08-19T12:36:00.991068300Z

Instant to number of Seconds in long format :- 
1660912560

Fractional Nanoseconds part from an Instant in integer format :- 
991068300

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to parse Instant in String form ?
Java 8 – How to form an Instant passing Seconds and Nanoseconds fields ?