Java 8 – How to get instantaneous moment at UTC/GMT using Instant ?

In this article, we will learn how to get instantaneous moment at GMT/UTC using Instant.now() method provided in Java 1.8 version

Get instantaneous moment at GMT/UTC from Clock :

  • There are 2 ways to get Instant at GMT/UTC
    1. Instant.now() – gets the current instant at the GMT/UTC from the system clock
    2. Instant.now(Clock) – gets the current instant at the GMT/UTC from the specified clock
  • Lets see an example to get current instant from system & specified clocks

GetUtcInstantFromClock.java

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

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;

public class GetUtcInstantFromClock {

	public static void main(String[] args) {

		// default zone
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("Default System Zone is = " 
				+ zoneId);

		// 1. get an instantaneous moment at GMT/UTC
		Instant instant = Instant.now();
		System.out.println("\nCurrent Instant at UTC/GMT using Instant.now() is   = " 
				+ instant);


		// 2. get an instantaneous moment at GMT/UTC passing Clock
		Clock clock = Clock.system(ZoneId.of("Europe/Paris"));
		Instant instant2 = Instant.now(clock);
		System.out.print("\nCurrent Instant at UTC/GMT using Instant & Clock is = " 
				+ instant2);
	}
}

Output:

Default System Zone is = Asia/Calcutta

Current Instant at UTC/GMT using Instant.now() is   = 2022-08-19T14:37:16.881925100Z

Current Instant at UTC/GMT using Instant & Clock is = 2022-08-19T14:37:16.898933Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form an Instant passing Seconds and Nanoseconds fields ?
Java 9 – Find difference between two ZonedDateTime instances upto nanosecond precision ?