how to convert from ZonedDateTime to Joda DateTime

Tim Pigden picture Tim Pigden · Jan 26, 2015 · Viewed 13.3k times · Source

I've switched to threeten for date times but I've still got a 3rd party tool that uses joda to write timestamp with timezone to the database and I need to convert from one to the other. What's the best way? As a workaround I tried DateTime.parse(zdt.toString) but it falls over because joda doesn't like the zone format

Invalid format: "2015-01-25T23:35:07.684Z[Europe/London]" is malformed at "[Europe/London]"

Answer

James Ding picture James Ding · May 20, 2016

Please notice that using DateTimeZone.forID(...) is not safe, which might throw DateTimeParseException as usually ZoneOffset.UTC has a ID "Z" which cannot be recognized by DateTimeZone.

What I would recommend in order to convert ZonedDateTime to DateTime is:

return new DateTime(
    zonedDateTime.toInstant().toEpochMilli(),
    DateTimeZone.forTimeZone(TimeZone.getTimeZone(zonedDateTime.getZone())));