Gili
Gili

Reputation: 90150

Converting TimeUnit to ChronoUnit?

Java 8 introduced ChronoUnit which is largely equivalent to TimeUnit introduced in Java 5.

Is there an existing function for converting a TimeUnit to ChronoUnit? (Yes, I know how to write my own)

Upvotes: 45

Views: 12921

Answers (3)

Cardinal System
Cardinal System

Reputation: 3430

Java 8

For those of us using Java 8, you can copy toChronoUnit from the TimeUnit source code in a later JDK and make it into a static method to achieve the same end:

public static ChronoUnit toChronoUnit(TimeUnit timeUnit) {
    switch (timeUnit) {
        case NANOSECONDS:
            return ChronoUnit.NANOS;
        case MICROSECONDS:
            return ChronoUnit.MICROS;
        case MILLISECONDS:
            return ChronoUnit.MILLIS;
        case SECONDS:
            return ChronoUnit.SECONDS;
        case MINUTES:
            return ChronoUnit.MINUTES;
        case HOURS:
            return ChronoUnit.HOURS;
        case DAYS:
            return ChronoUnit.DAYS;
        default:
            throw new AssertionError();
    }
}

Upvotes: 1

Chriss
Chriss

Reputation: 5639

Java 9

In Java 9 the TimeUnit API got extended and allows to convert between TimeUnit and ChronoUnit:

TimeUnit.toChronoUnit() // returns a ChronoUnit
TimeUnit.of(ChronoUnit chronoUnit) // returns a TimeUnit

see: JDK-8141452

Upvotes: 45

JodaStephen
JodaStephen

Reputation: 63455

At one stage during the development, you could could construct a Duration from a TimeUnit. https://github.com/ThreeTen/threeten/blob/3b4c40e3e7a5dd7a4993ee19e1c156e4e65432b3/src/main/java/javax/time/Duration.java#L293 However this was removed for the final version of the code in Java SE 8.

I don't know of any pre-packaged routine to do the conversion, but it should be added to ThreeTen-Extra, probably in Temporals.

UPDATE: This was fixed by https://github.com/ThreeTen/threeten-extra/issues/22

Upvotes: 14

Related Questions