I need to parse date in Java. I have String value 2018-05-15 09:32:51.550082 +3:00
and I need to parse it into date-time. I tried to parse to ZonedDateTime
, but I got an error at index 10. Tried to parse with DateTimeFormatter
parser ‘yyyy-MM-dd HH:mm:ss.SSSSSS Z’ and got error at index 26. Apparently my UTC offset of +3:00
cannot be parsed. How can I do this?
Advertisement
Answer
Java 9 and later allows:
String dateTimeString = "2018-05-15 09:32:51.550082 +3:00"; DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("uuuu-MM-dd HH:mm:ss.SSSSSS ") .appendOffset("+H:MM:ss", "+0:00") .toFormatter(); OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString, formatter); System.out.println(dateTime);
Output:
2018-05-15T09:32:51.550082+03:00
For Java 8 or the ThreeTen Backport you will probably have to prepare your date-time string before parsing it:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS XXX"); dateTimeString = dateTimeString.replaceFirst("([+-])(\d(?::\d\d){0,2})$", "$10$2");
The rest is as before and gives the same result. The replaceFirst
call inserts a 0
between the +
and 3:00
, but only if the hours were only one digit. The regular expression is hard to read, so you will prefer the Java 9 solution.
As already discussed in the comments the hard part is the offset of +3:00
. Java’s built-in formatters and the format pattern letters you can use for specifying your own format all require two-digit hours in the offset. The DateTimeFormatterBuilder.appendOffset
method that I am using allows a limited number of formats to be specified; 9 different formats in Java 8; 22 in Java 9. Link: Documentation of appendOffset()
.