Java 8 – How to form LocalDateTime passing Instant and ZoneId ?

In this article, we will learn how to form LocalDateTime passing Instant & ZoneId using LocalDateTime.ofInstant() method provided in Java 1.8 version

Form LocalDateTime passing Instant & ZoneId :

  • LocalDateTime.ofInstant(Instant, ZoneId) –
    • Obtains an instance of LocalDateTime from an Instant and Zone ID
  • Instant – get current moment/instant using Instant.now() method
  • ZoneId – get system default zone using ZoneId.systemDefault() method
  • Pass Instant & ZoneId obtained in above steps to the LocalDateTime.ofInstant() method which returns LocalDateTime
  • Finally, print LocalDateTime in different formatted style like SHORT & MEDIUM to the console

FormLocalDateTime3.java

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

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class FormLocalDateTime3 {

	public static void main(String[] args) {

		// 1. get current moment or Instant
		Instant instant = Instant.now();
		System.out.println("Instant :- " + instant);


		// 2. get default zone
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("ZoneId :- " + zoneId);


		// 3. form LocalDateTime passing current Instant & default ZoneId
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
		System.out.println("\nLocalDateTime :- " + localDateTime);


		// 3.1 format LocalDateTime in FormatStyle.SHORT
		String formattedStr1 = localDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT));
		System.out.println("\nLocalDateTime in FormatStyle.SHORT :- " + formattedStr1);


		// 3.2 format LocalDateTime in FormatStyle.MEDIUM
		String formattedStr2 = localDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
		System.out.print("LocalDateTime in FormatStyle.MEDIUM :- " + formattedStr2);
	}
}

Output:

Instant :- 2022-08-08T12:09:35.937192900Z
ZoneId :- Asia/Calcutta

LocalDateTime :- 2022-08-08T17:39:35.937192900

LocalDateTime in FormatStyle.SHORT :- 08/08/22, 5:39 pm
LocalDateTime in FormatStyle.MEDIUM :- 08-Aug-2022, 5:39:35 pm

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form LocalDateTime passing Second/Nano and ZoneOffset ?
Java 8 – How to form LocalDateTime passing LocalDate and LocalTime ?