Search code examples
javadatetimejava-timedatetime-conversionthreetenbp

How can I convert a org.threeten.bp.OffsetDateTime to java.time.OffsetDateTime?


I'm using a client library (third party, not mine, cannot change) which utilizes the ThreeTen date types. My project is Java 11 and uses Java 8 date types. What is the recommended way to convert ThreeTeen objects to their Java 8 counterparts?


Solution

  • There seems to be no built-in way to convert one instance to the other.

    I think you have write your own converters, like one of the following:

    Part-by-part conversion:

    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());
    }
    

    Parsing the formatted output of the other instance:

    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));
    }
    

    Haven't tested which one is more efficient...