Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ZonedDateTime format and parsing exception

I have a problem with parsing zoned date time:

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-ddzhh:mm");
ZonedDateTime.parse(s, formatter);

and error:

java.time.format.DateTimeParseException: Text ‘2022-05-24UTC12:15’
could not be parsed at index 10

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

whats wrong with this code ?

thanks

>Solution :

tl;dr – You have the wrong pattern…

The character z is not able to parse "UTC" because UTC is a time-zone ID while zcan only parse time-zone-names according to the JavaDocs of java.time.DateTimeFormatter, here’s the relevant part of the docs:

Symbol  Meaning                     Presentation      Examples
------  -------                     ------------      -------
(…)

V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
z       time-zone name              zone-name         Pacific Standard Time; PST

(…)

That means you have to parse it using the character V, but you will have to put two of them (VV) or you will get a nice IllegalArgumentException with the following message:

java.lang.IllegalArgumentException: Pattern letter count must be 2: V

This all boils down to the following pattern:

DateTimeFormatter format = DateTimeFormatter.ofPattern("uuuu-MM-ddVVHH:mm");

which will be able to parse an input like "2022-05-24UTC12:15".

Unfortunately, the docs don’t mention if UTC is actually an id or a name. Consider GMT, which also defines a time zone with an offset of 0 hours. Your current pattern (the one with a single z) would have parsed the input "2022-05-24GMT12:15", because GMT is considered a time-zone name.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading