Parsing a date using DateTimeFormatter ofPattern

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.

Answer

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’.

Leave a Reply

Your email address will not be published. Required fields are marked *