Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDateTime ZonedDateTime cannot parse date with time zone

I am trying to use Java 8 new Date pattern instead of Joda and I have the following problem:

Both

ZonedDateTime.parse("02/05/16 11:51.12.083 +04:30", DateTimeFormatter.ofPattern("dd/MM/yy HH:mm.ss.SSS Z"))

and

LocalDateTime.parse("02/05/16 11:51.12.083 +04:30", DateTimeFormatter.ofPattern("dd/MM/yy HH:mm.ss.SSS Z"))

throw 'java.time.format.DateTimeParseException' exception. While

org.joda.time.DateTime.parse("02/05/16 11:51.12.083 +04:30", DateTimeFormat.forPattern("dd/MM/yy HH:mm.ss.SSS Z"))

works fine.

Cause of the exception is:

java.time.format.DateTimeParseException: Text '02/05/16 11:51.12.083 +04:30' could not be parsed at index 22

Am I doing something wrong?

like image 661
ampofila Avatar asked May 16 '16 11:05

ampofila


1 Answers

If you read the javadoc of DateTimeFormatter, you will find a section detailing how to use the Z offset (emphasis mine):

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.

So using 5 Zs will work as expected:

ZonedDateTime.parse("02/05/16 11:51.12.083 +04:30",
                    DateTimeFormatter.ofPattern("dd/MM/yy HH:mm.ss.SSS ZZZZZ"));

Note that you can obtain similar results with:

  • z
  • zz
  • zzz
  • zzzz
  • xxx
  • XXX
  • xxxxx
  • XXXXX
like image 121
assylias Avatar answered Sep 26 '22 08:09

assylias