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

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

Form OffsetDateTime passing Date/Time/Offset fields :

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

FormOffsetDateTime.java

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

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

public class FormOffsetDateTime {

	public static void main(String[] args) {

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


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


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

Output:

OffsetDateTime :- 
2019-09-21T11:35:26.000000425+05:30

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

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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form OffsetDateTime passing LocalDate, LocalTime and ZoneOffset ?
Java 8 – How to get Date, Time and Offset fields from OffsetDateTime ?