< prev index next >

src/java.base/share/classes/java/util/concurrent/TimeUnit.java

Print this page

        

*** 33,42 **** --- 33,45 ---- * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; + import java.time.temporal.ChronoUnit; + import java.util.Objects; + /** * A {@code TimeUnit} represents time durations at a given unit of * granularity and provides utility methods to convert across units, * and to perform timing and delay operations in these units. A * {@code TimeUnit} does not maintain time information, but only
*** 388,393 **** --- 391,456 ---- int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); } } + /** + * Converts a {@code TimeUnit} to an equivalent {@code ChronoUnit}. + * + * @param timeUnit the timeUnit to convert, not null + * @return the converted equivalent chronoUnit + * @throws IllegalArgumentException if the unit cannot be converted + * @since 9 + */ + public static ChronoUnit toChronoUnit(TimeUnit timeUnit) { + Objects.requireNonNull(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 IllegalArgumentException("Unknown TimeUnit"); + } + } + + /** + * Converts a {@code ChronoUnit} to an equivalent {@code TimeUnit}. + * + * @param chronoUnit the unit to convert, not null + * @return the converted equivalent timeUnit + * @throws IllegalArgumentException if the unit cannot be converted + * @since 9 + */ + public static TimeUnit of(ChronoUnit chronoUnit) { + Objects.requireNonNull(chronoUnit, "chronoUnit"); + switch (chronoUnit) { + case NANOS: + return TimeUnit.NANOSECONDS; + case MICROS: + return TimeUnit.MICROSECONDS; + case MILLIS: + return TimeUnit.MILLISECONDS; + case SECONDS: + return TimeUnit.SECONDS; + case MINUTES: + return TimeUnit.MINUTES; + case HOURS: + return TimeUnit.HOURS; + case DAYS: + return TimeUnit.DAYS; + default: + throw new IllegalArgumentException("No TimeUnit equivalent for " + chronoUnit); + } + } + }
< prev index next >