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 :)
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;
See more on this question at Stackoverflow