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?
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 Z
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With