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

In this article, we will learn how to form ZonedDateTime passing Instant & Zone fields using ZonedDateTime.of() method provided in Java 1.8 version

Form ZonedDateTime passing Instant & Zone Fields :

  • ZonedDateTime.of() method returns ZonedDateTime passing Instant and Zone (Zone/Offset) fields
  • ZonedDateTime.of(Instant, ZoneId) –
    • Obtains an instance of ZonedDateTime from an Instant
  • Finally, print ZonedDateTime in different formatted style like SHORT, MEDIUM, LONG & FULL to the console

FormZonedDateTime4.java

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

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

public class FormZonedDateTime4 {

	public static void main(String[] args) {

		// 1. LocalDateTime
		Instant instant = Instant.now();
		System.out.println("Instant = \n" + instant);


		// 2. ZoneId
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("\nZoneId :- \n" + zoneId);


		// 3. form ZonedDateTime passing Instant & ZoneId
		ZonedDateTime zonedDateTime = ZonedDateTime
				.ofInstant(instant, zoneId);
		System.out.println("\nZonedDateTime :- \n" + zonedDateTime);


		// 3.1 format ZonedDateTime in FormatStyle.SHORT
		String formattedStr1 = zonedDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT));
		System.out.println("\nZonedDateTime in FormatStyle.SHORT :- \n" + formattedStr1);


		// 3.2 format ZonedDateTime in FormatStyle.MEDIUM
		String formattedStr2 = zonedDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
		System.out.println("\nZonedDateTime in FormatStyle.MEDIUM :- \n" + formattedStr2);


		// 3.3 format ZonedDateTime in FormatStyle.LONG
		String formattedStr3 = zonedDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG));
		System.out.println("\nZonedDateTime in FormatStyle.LONG :- \n" + formattedStr3);


		// 3.4 format ZonedDateTime in FormatStyle.FULL
		String formattedStr4 = zonedDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL));
		System.out.print("\nZonedDateTime in FormatStyle.FULL :- \n" + formattedStr4);
	}
}

Output:

Instant = 
2022-08-12T04:15:05.806136300Z

ZoneId :- 
Asia/Calcutta

ZonedDateTime :- 
2022-08-12T09:45:05.806136300+05:30[Asia/Calcutta]

ZonedDateTime in FormatStyle.SHORT :- 
12/08/22, 9:45 am

ZonedDateTime in FormatStyle.MEDIUM :- 
12-Aug-2022, 9:45:05 am

ZonedDateTime in FormatStyle.LONG :- 
12 August 2022 at 9:45:05 am IST

ZonedDateTime in FormatStyle.FULL :- 
Friday, 12 August, 2022 at 9:45:05 am India Standard Time

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to parse ZonedDateTime in String form ?
Java 8 – How to form ZonedDateTime passing LocalDateTime and ZoneId ?