Java Convert String to ZonedDateTime

Tags: String Java ZonedDateTime Java 8 DateTimeFormatter

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

Table of contents

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

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

In Java, we can use the ZonedDateTime.parse(CharSequence text) static method to parse a String value to a ZonedDateTime object as the Java code below.

ConvertStringToZonedDateTimeExample1.java

import java.time.ZonedDateTime;

public class ConvertStringToZonedDateTimeExample1 {
    public static void main(String... args) {
        ZonedDateTime zonedDateTime1 = ZonedDateTime.parse("2022-05-26T08:15:30+07:00[Asia/Ho_Chi_Minh]");
        ZonedDateTime zonedDateTime2 = ZonedDateTime.parse("2022-05-26T08:15:30+10:00[Australia/Sydney]");
        ZonedDateTime zonedDateTime3 = ZonedDateTime.parse("2022-05-26T08:15:30+02:00[Europe/Paris]");
        ZonedDateTime zonedDateTime4 = ZonedDateTime.parse("2022-05-26T08:15:30+09:00[Asia/Tokyo]");

        System.out.println(zonedDateTime1);
        System.out.println(zonedDateTime2);
        System.out.println(zonedDateTime3);
        System.out.println(zonedDateTime4);
    }
}
The output as below.
2022-05-26T08:15:30+07:00[Asia/Ho_Chi_Minh]
2022-05-26T08:15:30+10:00[Australia/Sydney]
2022-05-26T08:15:30+02:00[Europe/Paris]
2022-05-26T08:15:30+09:00[Asia/Tokyo]

How to convert String to ZonedDateTime with custom date time format

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

ConvertStringToZonedDateTimeExample2.java

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ConvertStringToZonedDateTimeExample2 {
    public static void main(String... args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
        ZonedDateTime zonedDateTime = ZonedDateTime.parse("2022-04-26 09:30:40 +07:00", dateTimeFormatter);

        System.out.println("ZonedDateTime: " + zonedDateTime);
    }
}
The output as below.
ZonedDateTime: 2022-04-26T09:30:40+07:00

Happy Coding 😊

Java Convert ZonedDateTime to Instant

Java Convert ZonedDateTime to Date

Java Convert ZonedDateTime to Calendar

Java Convert ZonedDateTime to LocalDateTime

Java Convert ZonedDateTime to OffsetDateTime

Java Convert ZonedDateTime to LocalTime

Java Convert ZonedDateTime to LocalDate

Java Convert ZonedDateTime to ZoneOffset

Java Convert ZonedDateTime to ZoneId

Java Convert ZonedDateTime to Epoch Seconds

Java Convert ZonedDateTime to String