我有一个存储joda时间DateTime对象的数据源。我需要将它们转换为java ZonedDateTime对象,并保留原始时区。
保持偏移量是不够的,因为某些DateTime对象表示每日重复任务,并且这些任务必须在每个日期的特定时区中的特定时间发生。因此,它们必须遵循指定的TimeZone过渡,例如夏季和冬季。我不能说出DateTime对象的最终用途,因此为了安全起见,我需要保留所有对象上的时区信息。
如何从org.joda.time.DateTime转换为java.time.ZonedDateTime?
将所有
ord.joda.time.DateTimeZone.getId()
映射到ID可用
java.time.ZoneId
并非来自Joda-Time的所有时区字符串都将匹配,java.time
但是绝大多数都将匹配,因为它们都基于IANA tz数据。比较DateTimeZone.getAvailableIDs()
以ZoneId.getAvailableZoneIds()
确定不匹配。可以使用映射其他标识符ZoneId.of(String, Map)
。
为了以最有效的方式进行主要转换,您必须传递每个字段:
ZonedDateTime zdt = ZonedDateTime.ofLocal(
LocalDateTime.of(
dt.getYear(),
dt.getMonthOfYear(),
dt.getDayOfMonth(),
dt.getHourOfDay(),
dt.getMinuteOfHour(),
dt.getSecondOfMinute(),
dt.getMillisOfSecond() * 1_000_000),
ZoneId.of(dt.getZone().getID(), ZoneId.SHORT_IDS),
ZoneOffset.ofTotalSeconds(dt.getZone().getOffset(dt) / 1000));
使用注意事项ZoneId.SHORT_IDS
作为Map
在这种情况下。
对于处理大多数用例但性能较低的较简单解决方案,请使用以下方法:
ZonedDateTime zdt = dt.toGregorianCalendar().toZonedDateTime();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句