Converting TimeUnit to ChronoUnit?
Asked Answered
S

3

45

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)

Siva answered 27/10, 2014 at 5:37 Comment(2)
You should note that not every ChronoUnit is mappable to TimeUnit, for example MONTHS. What will you do in this case?Compossible
@MenoHochschild, good point. I was actually only interested in one-way mapping. I will update the question accordingly.Siva
S
45

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

Severini answered 2/3, 2016 at 10:24 Comment(0)
R
14

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

Rubeola answered 27/10, 2014 at 7:39 Comment(3)
Thank you for the clarification. Are there plans to add this into the core API in the future?Siva
I don't have any immediate plans for this, but i t would make sense to do so.Rubeola
@Siva — Note that it was added to the core API in Java 9: https://mcmap.net/q/368618/-converting-timeunit-to-chronounitBelfry
P
1

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();
    }
}
Poltergeist answered 18/12, 2023 at 20:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.