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
whats wrong with this code ?
thanks
CodePudding user response:
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:
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".
CodePudding user response:
Yes it's because of formatter pattern, i suggest to use the code below :
final DateTimeFormatter format
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime
.parse("2022-05-24 14:30:30 -01:00", format);
System.out.println(zonedDateTime);
