0

I am trying to convert a date String from the server to dateTime with ThreeTenBP. My method looks like this:

String toDateTime(String dateString) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("M/d/yyyy h:mm a").toFormatter();
    ZonedDateTime dateTimeWithZone = ZonedDateTime.parse(dateString, formatter);
    return dateTimeWithZone.toString();
}

However, I get an exception:

DateTimeParseException: Text '2015-07-21T09:26:06.260-05:00' could not be parsed at index 4

What am I doing wrong?

1
  • 1
    Well, look at your pattern and look at the input string... Commented Jul 21, 2015 at 15:05

1 Answer 1

1

Your pattern begins with "M/" which would indicate the month. Your actual date string begins with "2015-" which is obviously the year. Actually that date looks like it's in ISO 8601 format and a pattern like "yyyy-MM-dd'T'HH:mm:ss.SSSX" would match.

Sign up to request clarification or add additional context in comments.

3 Comments

After trying your pattern, I get this error: Text '2015-07-21T09:26:06.260-05:00' could not be parsed at index 19
Just updated the answer. See docs.oracle.com/javase/7/docs/api/java/text/… for date pattern docs.
Ah, that nasty colon character in the timezone. Needs "X" instead of "Z" to parse that. I think that's only available with Java 7 and newer. Not sure they backported that with ThreeTenBP. Good luck!

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.