6 |
|
|
7 |
|
package java.util.concurrent; |
8 |
|
|
9 |
+ |
import java.time.temporal.ChronoUnit; |
10 |
+ |
import java.util.Objects; |
11 |
+ |
|
12 |
|
/** |
13 |
|
* A {@code TimeUnit} represents time durations at a given unit of |
14 |
|
* granularity and provides utility methods to convert across units, |
364 |
|
} |
365 |
|
} |
366 |
|
|
367 |
+ |
/** |
368 |
+ |
* Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}. |
369 |
+ |
* |
370 |
+ |
* @return the converted equivalent ChronoUnit |
371 |
+ |
* @since 9 |
372 |
+ |
*/ |
373 |
+ |
public ChronoUnit toChronoUnit() { |
374 |
+ |
switch (this) { |
375 |
+ |
case NANOSECONDS: return ChronoUnit.NANOS; |
376 |
+ |
case MICROSECONDS: return ChronoUnit.MICROS; |
377 |
+ |
case MILLISECONDS: return ChronoUnit.MILLIS; |
378 |
+ |
case SECONDS: return ChronoUnit.SECONDS; |
379 |
+ |
case MINUTES: return ChronoUnit.MINUTES; |
380 |
+ |
case HOURS: return ChronoUnit.HOURS; |
381 |
+ |
case DAYS: return ChronoUnit.DAYS; |
382 |
+ |
default: throw new AssertionError(); |
383 |
+ |
} |
384 |
+ |
} |
385 |
+ |
|
386 |
+ |
/** |
387 |
+ |
* Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}. |
388 |
+ |
* |
389 |
+ |
* @param chronoUnit the ChronoUnit to convert |
390 |
+ |
* @return the converted equivalent TimeUnit |
391 |
+ |
* @throws IllegalArgumentException if {@code chronoUnit} has no |
392 |
+ |
* equivalent TimeUnit |
393 |
+ |
* @throws NullPointerException if {@code chronoUnit} is null |
394 |
+ |
* @since 9 |
395 |
+ |
*/ |
396 |
+ |
public static TimeUnit of(ChronoUnit chronoUnit) { |
397 |
+ |
switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) { |
398 |
+ |
case NANOS: return TimeUnit.NANOSECONDS; |
399 |
+ |
case MICROS: return TimeUnit.MICROSECONDS; |
400 |
+ |
case MILLIS: return TimeUnit.MILLISECONDS; |
401 |
+ |
case SECONDS: return TimeUnit.SECONDS; |
402 |
+ |
case MINUTES: return TimeUnit.MINUTES; |
403 |
+ |
case HOURS: return TimeUnit.HOURS; |
404 |
+ |
case DAYS: return TimeUnit.DAYS; |
405 |
+ |
default: |
406 |
+ |
throw new IllegalArgumentException( |
407 |
+ |
"No TimeUnit equivalent for " + chronoUnit); |
408 |
+ |
} |
409 |
+ |
} |
410 |
+ |
|
411 |
|
} |