如何转换ZonedDateTime至Joda DateTime

Tim*_*den 8 java jodatime threetenbp

我已经切换到三个日期时间,但我仍然有一个第三方工具,使用joda将时区写入数据库的时区,我需要从一个转换为另一个.什么是最好的方式?作为一种解决方法,我尝试了DateTime.parse(zdt.toString)但是因为joda不喜欢区域格式而失败了

格式无效:"2015-01-25T23:35:07.684Z [欧洲/伦敦]"格格不入"[欧洲/伦敦]"

小智 14

请注意,使用DateTimeZone.forID(...)是不安全的,这可能会抛出DateTimeParseException,因为ZoneOffset.UTC通常具有ID"Z",而DateTimeZone无法识别它.

我建议将ZonedDateTime转换为DateTime是:

return new DateTime(
    zonedDateTime.toInstant().toEpochMilli(),
    DateTimeZone.forTimeZone(TimeZone.getTimeZone(zonedDateTime.getZone())));
Run Code Online (Sandbox Code Playgroud)


Men*_*ild 5

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
Run Code Online (Sandbox Code Playgroud)

如果区域ID转换对于任何不受支持或无法识别的ID可能崩溃,我建议

  • 捕捉并记录下来,
  • 进行tz存储库的更新(对于Joda:更新到最新版本,对于JDK:使用tz-updater-tool)

这通常是比仅默默地退回任何UTC等任意tz-offset更好的策略。