1

If my time unit is of type seconds and cycle duration is 20 sec after 86400/20 = 4320 cycles, 24 hours are passed.

long numberOfCyclesToReach24Hours(long cycleDuration, TimeUnit unit) {
    // if I knew that unit is of type seconds I could
    return TimeUnit.HOURS.toSeconds(24) / cycleDuration
    // but if it is of type MILLISECONDS for example I have to
    //return TimeUnit.HOURS.toMillis(24) / cycleDuration
}

Is there an elegant solution to this problem or I really have to switch case all of the types? I know it would not happen that often, but if in the future new TimeUnit type is introduced, the code has to be adapted :)

I was also thinking of something like using the TimeUnit.values method and relying on the order of the returned type and by checking the position of the input unit in it to know by which constant (1000L, 60L etc.) I could calculate the number of cycles on my own without any toSeconds, toMillis etc. methods, but this is even uglier and really strange :)

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
radio
  • 897
  • 2
  • 10
  • 25
  • Note that the first version of my answer was the wrong way round - I've fixed it now, but if you tried it with `TimeUnit.HOURS.convert(24, unit)` that would give the wrong answer. Sorry! – Jon Skeet Sep 28 '17 at 21:43

1 Answers1

3

It sounds like you're just looking for the convert method:

Converts the given time duration in the given unit to this unit.

return unit.convert(24, TimeUnit.HOURS) / cycleDuration;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • wow, I was pretty sure I checked all possible methods ot the TimeUnit enum. I guess I need a cup of coffee, thanks :) – radio Sep 28 '17 at 21:49