Java 8 – How to form OffsetDateTime passing LocalDate, LocalTime and ZoneOffset ?

In this article, we will learn how to form OffsetDateTime passing LocalDate & LocalTime & Offset fields using OffsetDateTime.of() method provided in Java 1.8 version

Form OffsetDateTime passing LocalDate, LocalTime & Offset fields :

  • OffsetDateTime.of() method returns OffsetDateTime passing LocalDate (Day/Month/Year) and LocalTime (Hour/Minute/Second/Nanosecond) and Offset fields
  • OffsetDateTime.of(LocalDate, LocalTime, ZoneOffset) –
    • Obtains an instance of OffsetDateTime from a LocalDate/LocalTime and ZoneOffset
  • Finally, print OffsetDateTime in different formatted style like SHORT & MEDIUM to the console

FormOffsetDateTime2.java

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

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class FormOffsetDateTime2 {

	public static void main(String[] args) {

		// 1. LocalDate
		LocalDate localDate = LocalDate.now();
		System.out.println("LocalDate :- \n" + localDate);


		// 2. LocalDate
		LocalTime localTime = LocalTime.now();
		System.out.println("\nLocalTime :- \n" + localTime);


		// 3. ZoneOffset
		ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
		System.out.println("\nZoneOffset :- \n" + zoneOffset);


		// 4. form OffsetDateTime passing LocalDate & LocalTime & ZoneOffset
		OffsetDateTime offsetDateTime = OffsetDateTime
				.of(localDate, localTime, zoneOffset);
		System.out.println("\nOffsetDateTime :- \n" + offsetDateTime);


		// 4.1 format OffsetDateTime in FormatStyle.SHORT
		String formattedStr1 = offsetDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT));
		System.out.println("\nOffsetDateTime in FormatStyle.SHORT :- \n" + formattedStr1);


		// 4.2 format OffsetDateTime in FormatStyle.MEDIUM
		String formattedStr2 = offsetDateTime.format(
				DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
		System.out.print("\nOffsetDateTime in FormatStyle.MEDIUM :- \n" + formattedStr2);
	}
}

Output:

LocalDate :- 
2022-08-17

LocalTime :- 
08:32:14.258036100

ZoneOffset :- 
+05:30

OffsetDateTime :- 
2022-08-17T08:32:14.258036100+05:30

OffsetDateTime in FormatStyle.SHORT :- 
17/08/22, 8:32 am

OffsetDateTime in FormatStyle.MEDIUM :- 
17-Aug-2022, 8:32:14 am

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form OffsetDateTime passing LocalDateTime and ZoneOffset ?
Java 8 – How to form OffsetDateTime passing Date, Time and Offset fields ?