Java Convert String to OffsetDateTime

Tags: Java OffsetDateTime Java 8

In this Java core tutorial we learn how to convert a String to java.time.OffsetDateTime object in Java programming language with different solutions and Java example codes.

Table of contents

  1. How to convert String to OffsetDateTime using OffsetDateTime.parse() method
  2. How to convert String to OffsetDateTime with custom date time format

How to convert String to OffsetDateTime using OffsetDateTime.parse() method

In Java, we can use the OffsetDateTime.parse(CharSequence text) static method to parse a String in ISO-8601 extended offset date-time format to a OffsetDateTime object as the Java code below.

ConvertStringToOffsetDateTimeExample1.java

import java.time.OffsetDateTime;

public class ConvertStringToOffsetDateTimeExample1 {
    public static void main(String... args) {
        OffsetDateTime offsetDateTime1 = OffsetDateTime.parse("2022-05-14T14:20:32.111222400+07:00");
        OffsetDateTime offsetDateTime2 = OffsetDateTime.parse("2022-05-15T14:30:50.222333400+02:00");
        OffsetDateTime offsetDateTime3 = OffsetDateTime.parse("2022-07-11T08:30:50.333555400+10:00");

        System.out.println(offsetDateTime1);
        System.out.println(offsetDateTime2);
        System.out.println(offsetDateTime3);
    }
}
The output as below.
2022-05-14T14:20:32.111222400+07:00
2022-05-15T14:30:50.222333400+02:00
2022-07-11T08:30:50.333555400+10:00

How to convert String to OffsetDateTime with custom date time format

Using the java.time.format.DateTimeFormatter class we convert a String in specified date time format to OffsetDateTime object as the following example Java code.

ConvertStringToOffsetDateTimeExample2.java

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

public class ConvertStringToOffsetDateTimeExample2 {
    public static void main(String... args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z");
        OffsetDateTime offsetDateTime1 = OffsetDateTime.parse("11/07/2022 07:20:30 +07:00", dateTimeFormatter);

        System.out.println(offsetDateTime1);
    }
}
The output as below.
2022-07-11T07:20:30+07:00

Happy Coding 😊

Java Convert OffsetDateTime to Epoch Seconds

Java Convert OffsetDateTime to ZoneOffset

Java Convert OffsetDateTime to LocalDate

Java Convert OffsetDateTime to LocalTime

Java Convert OffsetDateTime to LocalDateTime

Java Convert OffsetDateTime to ZonedDateTime

Java Convert OffsetDateTime to Instant

Java Convert OffsetDateTime to Date

Java Convert OffsetDateTime to Calendar

Java Convert OffsetDateTime to OffsetTime

Java Convert OffsetDateTime to String

Java Convert Date to OffsetDateTime

Java Convert Calendar to OffsetDateTime