ZonedDateTime parse()

Java 8 ZonedDateTime class represents a date without associated timezone information. Learn to convert a date in string to ZonedDateTime object in Java 8 using ZonedDateTime parse() method.

1. String to ZonedDateTime example – default and custom patterns

Java example to convert a string into ZonedDateTime.

// Default pattern

ZonedDateTime today = ZonedDateTime.parse("2019-04-01T16:24:11.252+05:30[Asia/Calcutta]");
System.out.println(today);

// Custom pattern

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a z");
ZonedDateTime dateTime = ZonedDateTime.parse("2019-03-27 10:15:30 AM +05:30", formatter);
System.out.println(dateTime);

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss z");
ZonedDateTime dateTime1 = ZonedDateTime.parse("Mon, 1 Apr 2019 11:05:30 GMT", formatter1);
System.out.println(dateTime1);

Program output.

2019-04-01T16:24:11.252+05:30[Asia/Calcutta]
2019-03-27T10:15:30+05:30
2019-04-01T11:05:30Z[GMT]

2. Patterns

2.1. Default pattern

The default date pattern is DateTimeFormatter.ISO_ZONED_DATE_TIME.

The format consists of:

  • The ISO_LOCAL_DATE
  • The letter ‘T’. Parsing is case insensitive.
  • The ISO_LOCAL_TIME
  • The offset ID. If the offset has seconds then they will be handled even though this is not part of the ISO-8601 standard. Parsing is case insensitive.
  • If the zone ID is not available or is a ZoneOffset then the format is complete.
  • An open square bracket ‘[‘.
  • The zone ID. This is not part of the ISO-8601 standard. Parsing is case sensitive.
  • A close square bracket ‘]’.

2.2. Useful pattern

There are other useful built-in patterns which we can use to parse dates to ZonedDateTime instances.

  • RFC_1123_DATE_TIME – The RFC-1123 date-time formatter, such as ‘Tue, 3 Jun 2008 11:05:30 GMT‘.
  • ISO_OFFSET_DATE_TIME – The ISO date-time formatter that formats or parses a date-time with an offset, such as ‘2011-12-03T10:15:30+01:00‘.
  • ISO_ZONED_DATE_TIME – The ISO-like date-time formatter that formats or parses a date-time with offset and zone, such as ‘2011-12-03T10:15:30+01:00[Europe/Paris]’.

Drop me your questions related to string to zoned local date time conversion in Java 8 – in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.