Java 8 – How to convert OffsetDateTime to an Instant ?

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

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

Convert OffsetDateTime to an Instant :

  • OffsetDateTime has a method toInstant() which returns Instant
    • toInstant() – Converts invoking OffsetDateTime to an Instant
  • Using this method, it is very easy to convert OffsetDateTime to an Instant
  • After conversion, Instant will represent instantaneous/current moment at GMT/UTC
  • Lets see an example for conversion of OffsetDateTime to an Instant in the below illustration

ConvertOffsetDateTimeToInstant.java

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

import java.time.Instant;
import java.time.OffsetDateTime;

public class ConvertOffsetDateTimeToInstant {

	public static void main(String[] args) {

		// 1. get Offset Date/time
		OffsetDateTime offsetDateTime = OffsetDateTime.now();
		System.out.println("Offset Date/time is :- \n" 
				+ offsetDateTime);


		// 2. get Zone
		System.out.println("\nOffset is :- \n" 
				+ offsetDateTime.getOffset());


		// 3. convert OffsetDateTime to an Instant using toInstant()
		Instant instant = offsetDateTime.toInstant();
		System.out.print("\nConversion of OffsetDateTime to an Instant is :- \n"
				+ instant);
	}
}

Output:

Offset Date/time is :- 
2022-08-17T09:15:42.382278700+05:30

Offset is :- 
+05:30

Conversion of OffsetDateTime to an Instant is :- 
2022-08-17T03:45:42.382278700Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to extract LocalDate and LocalTime and LocalDateTime from OffsetDateTime ?
Java 8 – How to convert OffsetDateTime to ZonedDateTime ?