Java 8 – How to convert ZonedDateTime to an OffsetDateTime ?

In this article, we will learn how to convert ZonedDateTime to an OffsetDateTime using toOffsetDateTime() method of ZonedDateTime provided in Java 1.8 version

For OffsetDateTime to ZonedDateTime conversion, read Java 8 – How to convert OffsetDateTime to ZonedDateTime ?

Convert ZonedDateTime to an OffsetDateTime :

  • ZonedDateTime has a method toOffsetDateTime() which returns OffsetDateTime
    • toOffsetDateTime() – Converts invoking ZonedDateTime to an OffsetDateTime
  • Using this method, it is very easy to convert ZonedDateTime to an OffsetDateTime
  • After conversion, OffsetDateTime have Date & Time parts same as that of ZonedDateTime
  • Lets see an example for conversion of ZonedDateTime to an OffsetDateTime in the below illustration

ConvertZonedDateTimeToOffsetDateTime.java

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

import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

public class ConvertZonedDateTimeToOffsetDateTime {

	public static void main(String[] args) {

		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("Zoned Date/time is :- \n" 
				+ zonedDateTime);


		// 2. get Zone
		System.out.println("\nZone is :- \n" 
				+ zonedDateTime.getZone());


		// 3. convert ZonedDateTime to OffsetDateTime using toOffsetDateTime()
		OffsetDateTime offsetDateTime = zonedDateTime.toOffsetDateTime();
		System.out.print("\nConversion of ZonedDateTime to OffsetDateTime is :- \n"
				+ offsetDateTime);
	}
}

Output:

Zoned Date/time is :- 
2022-08-13T15:14:48.761717100+05:30[Asia/Calcutta]

Zone is :- 
Asia/Calcutta

Conversion of ZonedDateTime to OffsetDateTime is :- 
2022-08-13T15:14:48.761717100+05:30

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert ZonedDateTime to an Instant ?
Java 8 – How to convert ZonedDateTime to LocalDateTime ?