Home > Software design >  How to convert from long TimeUnit to Duration?
How to convert from long TimeUnit to Duration?

Time:06-17

I'm migrating some signatures from f(long dur, TimeUnit timeUnit) to f(Duration duration), and would like to implement the former with the latter.

Being on Java 8, I can't find any API to easily convert the long TU to a Duration, the only idea that comes to me is to do something ugly like:

static Duration convert(long dur, TimeUnit timeUnit) {
  switch (timeUnit) {
    case DAYS:
      return Duration.ofDays(dur);
    case HOURS:
      /* alternative, but (again) I don't have an easy conversion from TimeUnit -> ChronoUnit */
      return Duration.of(dur, ChronoUnit.HOURS);
    case ..... /* and so on */
  }
}

Or did I miss some API?

CodePudding user response:

Java 9

You can use static method Duration.of(long, TemporalUnit).

It expects an amount as long, and a TemporalUnit, so you need to convert the TimeUnit into ChronoUnit.

static Duration convert(long dur, TimeUnit timeUnit) {
    return Duration.of(dur, timeUnit.toChronoUnit());
}

Method toChronoUnit() was introduced in JDK version 9.

Java 8

With Java 8 you can translate TimeUnit into ChronoUnit using ThreeTen library's utility method Temporals.chronoUnit​(TimeUnit)

  • Related