Skip to content
Advertisement

Java DateTimeFormatter parsing with special characters

I’m having some troubles getting my format right for using DataTimeFormatter to parse a date time String in the format of:

20200915095318.883[-4:EDT]

I have a DateTimeFormatter pattern that works to produce this format, but it doesn’t work to parse the same String. That pattern is:

yyyyMMddHHmmss.SSS'['x':'z']'

If there are other libraries for DateTime parsing that are more appropriate for this type of need I’ll happily consider those as well. Right now my solution is a one off regex matcher for when I encounter this DateTime String and to manually build its parts. Which is gross.

Advertisement

Answer

Your only problem is that the -4 in your string needs a leading zero, as @deHaar indicated in his comment, i.e.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss.SSS'['x':'z']'");
LocalDateTime ldt = LocalDateTime.parse("20200915095318.883[-04:EDT]", formatter);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement