How to convert from ZonedDateTime to Joda DateTime

I switched to threeten on a date, but I still have a third-party tool that uses joda to write timestamps with time zones to the database, and I need to convert from one to another. What is the best way? As a workaround, I tried using DateTime.parse (zdt.toString), but it crashes because joda doesn't like the zone format

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

+7
source share
3 answers
ZonedDateTime zdt = ZonedDateTime.of( 2015, 1, 25, 23, 35, 7, 684000000, ZoneId.of("Europe/London")); System.out.println(zdt); // 2015-01-25T23:35:07.684Z[Europe/London] System.out.println(zdt.getZone().getId()); // Europe/London System.out.println(zdt.toInstant().toEpochMilli()); // 1422228907684 DateTimeZone london = DateTimeZone.forID(zdt.getZone().getId()); DateTime dt = new DateTime(zdt.toInstant().toEpochMilli(), london); System.out.println(dt); // 2015-01-25T23:35:07.684Z 

In the event that zone ID conversion may fail for any unsupported or unrecognized identifier, I recommend

  • catch and log
  • make updates to tz repositories (for Joda: upgrade to the latest version, for JDK: use tz-updater-tool)

This is usually a better strategy than just silence back to any arbitrary tz-offset, like UTC.

+4
source

Note that using DateTimeZone.forID (...) is unsafe, which can throw a DateTimeParseException, as usual, ZoneOffset.UTC has the identifier "Z" that DateTimeZone cannot recognize.

What I would recommend for converting ZonedDateTime to DateTime would be:

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

here is the kotlin extension to do the same (in case you code like this)

 fun ZonedDateTime.toDateTime(): DateTime = DateTime(this.toInstant().toEpochMilli(), DateTimeZone.forTimeZone(TimeZone.getTimeZone(this.zone))) 
+1
source

Source: https://habr.com/ru/post/1211896/


All Articles