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

In this article, we will learn how to form an Instant passing Seconds & Nanoseconds using Instant.ofEpochSecond() method provided in Java 1.8 version

Form an Instant passing Seconds/Nanos :

  • There are 2 methods available to form an Instant passing Seconds/Nanos
    1. ofEpochSecond(epochSecond) –
      • gets an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z
    2. ofEpochSecond(epochSecond, nanoAdjustment) –
      • gets an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second
  • Lets see an example to form an instant passing Seconds & Nanoseconds

FormUtcInstantUsingSecondAndNano.java

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

import java.time.Instant;

public class FormUtcInstantUsingSecondAndNano {

	public static void main(String[] args) {

		// 1. form an Instant passing Second/Nanos
		Instant instant1 = Instant.ofEpochSecond(1660818209, 443097123);
		System.out.println("Instant using Seconds/Nanos is = " + instant1);


		// 2. form an Instant passing only Seconds
		Instant instant2 = Instant.ofEpochSecond(1660818209);
		System.out.print("\nInstant using Seconds only is  = " + instant2);
	}
}

Output:

Instant using Seconds/Nanos is = 2022-08-18T10:23:29.443097123Z

Instant using Seconds only is  = 2022-08-18T10:23:29Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to get Seconds and Nanoseconds from an Instant ?
Java 8 – How to get instantaneous moment at UTC/GMT using Instant ?