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?

IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147

1 Answers1

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.

emu
  • 399
  • 2
  • 6
  • After trying your pattern, I get this error: `Text '2015-07-21T09:26:06.260-05:00' could not be parsed at index 19` – IgorGanapolsky Jul 21 '15 at 15:18
  • Just updated the answer. See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for date pattern docs. – emu Jul 21 '15 at 15:25
  • 1
    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! – emu Jul 21 '15 at 15:37