Reputation: 899
I'm trying to parse a string containing a date and time using the java.time.format.DateTimeFormatter
(my ultimate goal is to get the date from this string into a java.time.LocalDate
).
I keep getting DateTimeParseExceptions when trying to parse the date. Can someone help please?
The date is in the format "2015-07-14T11:42:12.000+01:00".
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-ddTHH:mm:ss.SSSZ");
LocalDateTime temp = LocalDateTime.ofInstant(Instant.from(f.parse(this.dateCreated)),
ZoneId.systemDefault());
LocalDate localDate = temp.toLocalDate();
I've tried different variations in the ofPattern, such as trying to escape the T by surrounding it with single quotes (as done above), and doing the same with the . and I've tried escaping both at the same time.
Do the colons need escaping too?
Appreciate any help with this.
Upvotes: 13
Views: 55227
Reputation: 338564
OffsetDateTime.parse( "2015-07-14T11:42:12.000+01:00" ) // No pattern needed.
Your input string complies with the ISO 8601 standard for date-time formats.
The java.time classes use ISO 8601 formats by default when parsing/generating text. So no need for you to define a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2015-07-14T11:42:12.000+01:00" ) ;
Upvotes: 2
Reputation: 9648
It should be
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
//or
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
instead of
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-ddTHH:mm:ss.SSSZ");
From JAVADoc:
Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.
Upvotes: 16
Reputation: 7790
Both "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" and "yyyy-MM-dd'T'HH:mm:ss.SSSVV" would work. Note that 5 Zs work but no less
Upvotes: 2