Java 8 – How to form ZonedDateTime passing Date, Time and Zone fields ?

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

Form ZonedDateTime passing Date/Time/Zone Fields :

  • ZonedDateTime.of() method returns ZonedDateTime passing Date (Day/Month/Year) and Time (Hour/Minute/Second/Nanosecond) and Zone (Zone/Offset) fields
  • ZonedDateTime.of(year, Month, dayOfMonth, hour, minute, second, nanoOfSecond, ZoneId) –
    • Obtains an instance of ZonedDateTime from a year, month, day, hour, minute, second, nanosecond and time-zone
  • Finally, print ZonedDateTime in different formatted style like SHORT, MEDIUM, LONG & FULL to the console

FormZonedDateTime.java

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

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

public class FormZonedDateTime {

	public static void main(String[] args) {

		// form ZonedDateTime passing Date(year/month/day) & Time(hour/minute/second/nano)
		ZonedDateTime zonedDateTime = ZonedDateTime
				.of(2019, 9, 21, 11, 35, 26, 425, ZoneId.systemDefault());
		System.out.println("ZonedDateTime :- \n" + zonedDateTime);


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


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


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


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

Output:

ZonedDateTime :- 
2019-09-21T11:35:26.000000425+05:30[Asia/Calcutta]

ZonedDateTime in FormatStyle.SHORT :- 
21/09/19, 11:35 am

ZonedDateTime in FormatStyle.MEDIUM :- 
21-Sep-2019, 11:35:26 am

ZonedDateTime in FormatStyle.LONG :- 
21 September 2019 at 11:35:26 am IST

ZonedDateTime in FormatStyle.FULL :- 
Saturday, 21 September, 2019 at 11:35:26 am India Standard Time

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form ZonedDateTime passing LocalDate, LocalTime and ZoneId ?
Java 8 – How to get Date, Time and Zone fields from ZonedDateTime ?