Convert String to ZonedDateTime in Java

ZonedDateTime class provides below APIs to convert or parse String to ZonedDateTime in java.
  • static ZonedDateTime parse(CharSequence text) - Obtains an instance of ZonedDateTime from a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris].
  • static ZonedDateTime parse(CharSequence text, DateTimeFormatter formatter) - Obtains an instance of ZonedDateTime from a text string using a specific formatter.

Java Convert String to ZonedDateTime Example

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

/**
 * Program to demonstrate ZonedDateTime Class APIs.
 * @author javaguides.net
 *
 */
public class ZonedDateTimeExample {
 
    public static void main(String[] args) {
        convertOrParseStringtoZonedDateTime();
    }

    private static void convertOrParseStringtoZonedDateTime() {
         // ISO date time
        ZonedDateTime dt1 = ZonedDateTime.parse("2017-03-28T12:25:38.492+05:30[Asia/Calcutta]",
        DateTimeFormatter.ISO_ZONED_DATE_TIME);
        System.out.println(dt1);

        // 'yyyy-MMM-dd HH:mm:ss' pattern
        ZonedDateTime dt2 = ZonedDateTime.parse("2017-May-02 23:35:05",
        DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss").withZone(ZoneId.of("UTC")));
        System.out.println(dt2);

       // 'yyyy-MM-dd KK:mm:ss a' pattern
        ZonedDateTime dt3 = ZonedDateTime.parse("2017-05-30 10:20:30 AM",
        DateTimeFormatter.ofPattern("yyyy-MM-dd KK:mm:ss a").withZone(ZoneId.systemDefault()));
        System.out.println(dt3);

       // 'cccc, MMMM dd, yyyy KK:mm a' pattern
       ZonedDateTime dt4 = ZonedDateTime.parse("Wednesday, May 31, 2017 10:21 PM",
       DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a").withZone(ZoneId.of("Europe/Paris")));
       System.out.println(dt4);
    }
}
Output:
2017-03-28T12:25:38.492+05:30[Asia/Calcutta]
2017-05-02T23:35:05Z[UTC]
2017-05-30T10:20:30+05:30[Asia/Calcutta]
2017-05-31T22:21+02:00[Europe/Paris]

Reference

Comments