How to Convert an Instant to Java 8 OffsetDateTime

The Java 8 OffsetDateTime is an immutable date-time object representing date and time with an offset from UTC/Greenwich in the ISO-8601 calendar system.

You can use the OffsetDateTime.ofInstant(instant) function to convert an Instant to Java 8 OffsetDateTime object.

In this tutorial, you will learn about converting Instant value to Java 8 OffsetDateTime object and vice versa in detail.

Convert Instant to OffsetDateTime

The OffsetDateTime provides the OffsetDateTime.ofInstant(instant) method to convert an Instant value to OffsetDateTime object.

Code

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

    //main
    Instant instant = Instant.ofEpochMilli(1642001214000L);  
    OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(instant, ZoneId.systemDefault());  
    System.out.println(offsetDateTime);   //2022-01-12T15:26:54Z

The above example converts the current Instant time to the OffsetDateTime object.

Convert OffsetDateTime to Instant

The Java 8 OffsetDateTime class provides the .toInstant() method to convert the OffsetDateTime value to an Instant object.

Code

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

    //main
    Instant instant = OffsetDateTime.now().toInstant();  
    System.out.println(instant);  //2023-01-29T18:15:21.013677100Z

    Instant instant = OffsetDateTime.of(2000, 1,2,3,4,5,6,ZoneOffset.UTC).toInstant();  
    System.out.println(instant);  //2000-01-02T03:04:05.000000006Z

The current time OffsetDateTime value is converted to the Instant value.

To convert an Instant to Java 8 ZonedDateTime, check this tutorial How to convert an Instant to Java 8 ZonedDateTime

Related Topics

Leave a Comment