1

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.

3
  • The zone offset parser expects the offset to be in the format -05:00 (with a :) Commented Apr 11, 2016 at 6:53
  • Java-8 does not have a type DateTime. Maybe you have confused this with Joda-Time. The Java-8-equivalent would be ZonedDateTime (or OffsetDateTime in this case). Commented Apr 11, 2016 at 13:46
  • @MenoHochschild My mistake, I meant a LocalDateTime object. Commented Apr 11, 2016 at 14:11

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

The solution to your problem should look something like this:

String ts = "2016-04-11T22:56:00.000-0500";
ZonedDateTime zdt = ZonedDateTime.parse(ts, DateTimeFormatter.ISO_OFFSET_DATE_TIME);

2 Comments

Getting the following exception (using Java 1.8_77 for context) and I assume the complaint is in regard to the hyphen character before the zoned offset: Exception in thread "main" java.time.format.DateTimeParseException: Text '2016-04-11T22:56:00.000-0500' could not be parsed at index 23 at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source) at java.time.format.DateTimeFormatter.parse(Unknown Source) at java.time.ZonedDateTime.parse(Unknown Source)
The provided formatter, ISO_OFFSET_DATE_TIME, is likely not defined to handle fractional seconds, which appear in your test string. It also likely expects a colon between the hours and minutes in the offset. You will therefore need to construct your own formatter to handle this case by using the DateTimeFormatter.ofPattern( ) function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.