首页 > 解决方案 > 如何将 org.threeten.bp.OffsetDateTime 转换为 java.time.OffsetDateTime?

问题描述

我正在使用使用 ThreeTen 日期类型的客户端库(第三方,不是我的,无法更改)。我的项目是 Java 11 并使用 Java 8 日期类型。将 ThreeTeen 对象转换为 Java 8 对象的推荐方法是什么?

标签: javadatetimejava-timedatetime-conversionthreetenbp

解决方案


似乎没有将一个实例转换为另一个实例的内置方法。

我认为您已经编写了自己的转换器,例如以下之一:

逐部分转换:

public static java.time.OffsetDateTime convertFrom(org.threeten.bp.OffsetDateTime ttOdt) {
    // convert the instance part by part...
    return java.time.OffsetDateTime.of(ttOdt.getYear(), ttOdt.getMonthValue(),
            ttOdt.getDayOfMonth(), ttOdt.getHour(), ttOdt.getMinute(),
            ttOdt.getSecond(), ttOdt.getNano(),
            // ZoneOffset isn't compatible, create one using the seconds of the given
            java.time.ZoneOffset.ofTotalSeconds(ttOdt.getOffset().getTotalSeconds());
}

解析另一个实例的格式化输出:

public static java.time.OffsetDateTime convertFrom(org.threeten.bp.OffsetDateTime ttOdt) {
    // convert the instance by parsing the formatted output of the given instance
    return java.time.OffsetDateTime.parse(
            ttOdt.format(org.threeten.bp.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}

还没有测试哪个更有效...


推荐阅读