javaandroidtimemillisecondstimeunit

Java/Android: Native API to transform hours, minutes and seconds in milliseconds


I have created my own method to transform hours, minutes and seconds in milliseconds. It seems to work fine.

I would prefer to use some Java/Android API to do this task.

TimeUnit provides me the reverse: milliseconds to hours, minutes and seconds.

Here goes my code:

class SomeUtilsClass {
    public static long toMilliseconds(int hours, int minutes, int seconds) {
        return ((hours * 60 * 60) + (minutes * 60) + seconds) * 1000;
    }
}

Solution

  • Your code looks fine and should work perfectly, but if you want to use Java/Android API to do this task you can change your function like this:

        public static long toMilliseconds(int hours, int minutes, int seconds) {
                return (TimeUnit.HOURS.toMillis(hours) + TimeUnit.MINUTES.toMillis(minutes) + TimeUnit.SECONDS.toMillis(seconds));
        }
    

    PS: You'll have the same result with both functions.