如何从ZonedDateTime转换为Joda DateTime [英] how to convert from ZonedDateTime to Joda DateTime
问题描述
我已将日期时间切换为三点钟,但我仍然有一个第三方工具,该工具使用joda将带有时区的时间戳记写入数据库,并且需要从一个转换为另一个. 最好的方法是什么? 作为一种解决方法,我尝试使用DateTime.parse(zdt.toString),但由于joda不喜欢区域格式而失败了
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
无效格式:"[欧洲/伦敦]"格式错误的"2015-01-25T23:35:07.684Z [欧洲/伦敦]"
Invalid format: "2015-01-25T23:35:07.684Z[Europe/London]" is malformed at "[Europe/London]"
推荐答案
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
如果区域ID转换可能因任何不受支持或无法识别的ID而崩溃,我建议
In case the zone id transformation might crash for any unsupported or unrecognized id, I recommend to
- 捕获并记录它,
- 更新tz储存库(对于Joda:更新到最新版本,对于JDK:使用tz-updater-tool)
通常,比静默地回落到任意UTC之类的tz-offset更好的策略.
That is usually the better strategy than to just silently fall back to any arbitrary tz-offset like UTC.
这篇关于如何从ZonedDateTime转换为Joda DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!