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)
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)
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
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
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();
}
}
© 2022 - 2024 — McMap. All rights reserved.
ChronoUnit
is mappable toTimeUnit
, for exampleMONTHS
. What will you do in this case? – Compossible