Search code examples
javajava-8java-timetimeunitchronounit

How to convert from long+TimeUnit to Duration?


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?


Solution

  • For Java 8 there is a roundabout solution :\ (we unnecessarily convert from our TU -> millis (or whatever unit) -> Duration) like this:

    long dur = ...
    TimeUnit unit = ...
    Duration result = Duration.ofMillis(unit.toMillis(dur));
    

    Caveat emptor with extremely large values though, Long.MAX_VALUE days cannot be correctly converted into long millis (compared to Duration's ctor that does throw when trying to init with such a value):

    final long millis = TimeUnit.DAYS.toMillis(Long.MAX_VALUE); // ouch
    final Duration dur = Duration.ofMillis(dur);
    System.err.println(dur.toDays() == Long.MAX_VALUE); // returns 'false'