Search code examples
javadatetimejava-8java-timezoneddatetime

Convert string to DateTime object with Java 8


I want to covert the following string with a zoned offset to a type DateTime with the new Java 8 time library in the simplest way possible:

2016-04-11T22:56:00.000-0500

I've experimented with the ISO_OFFSET_DATE_TIME format and ZonedDateTime objects, but I just can't seem to find a simple way to do it. Thanks in advance.


Solution

  • I don't think you'll find a built-in formatter to parse that string, but it is fairly straightforward to create one:

    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSx");
    OffsetDateTime date = OffsetDateTime.parse("2016-04-11T22:56:00.000-0500", fmt);