Get only hours and minutes Java

765 views Asked by At

I have problem. I need to calculate only hours and minutes, not days

import java.util.concurrent.TimeUnit;

public class TimeUtils {
    public static String millisecondToFullTime(long millisecond) {
        return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
    }

    public static String secondToFullTime(long second) {
        return timeUnitToFullTime(second, TimeUnit.SECONDS);
    }

    public static String minutesToFullTime(long minutes) {
        return timeUnitToFullTime(minutes, TimeUnit.MINUTES);
    }

    public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
        long day = timeUnit.toDays(time);
        long hour = timeUnit.toHours(time) % 24;
        long minute = timeUnit.toMinutes(time) % 60;
        long second = timeUnit.toSeconds(time) % 60;


        if (day > 0) {
            return String.format("%d day %02d:%02d:%02d", day, hour, minute, second);
        } else if (hour > 0) {
            return String.format("%d:%02d:%02d", hour, minute, second);
        } else if (minute > 0) {
            return String.format("%d:%02d", minute, second);
        } else {
            return String.format("%02d", second);
        }
    }
}

How this code can calculte only hours and minutes in java? Right now i get result in hours and minutes. Some functions return millisecondToFullTime and some return minutes To full time. If i comment out the day if clause it will not calculate correctly.

If the argument is equivalent of 1 day 5 hours 30 minutes, it should return 29:30:00.

1

There are 1 answers

0
acm On

You need to remove the module operation from long hour = timeUnit.toHours(time) % 24; as that will calculate the time in hours and remove everything related to day. Your method will end up as follows:

public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
    long hour = timeUnit.toHours(time);
    long minute = timeUnit.toMinutes(time) % 60;
    long second = timeUnit.toSeconds(time) % 60;

    if (hour > 0) {
        return String.format("%d:%02d:%02d", hour, minute, second);
    } else if (minute > 0) {
        return String.format("%d:%02d", minute, second);
    } else {
        return String.format("%02d", second);
    }
}