0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
anduplats
  • 885
  • 2
  • 14
  • 24
  • 1
    What is your desired result? If the argument is equivalent of 1 day 5 hours 30 minutes, do you want 29:30:00 or just 5:30:00? – Ole V.V. Apr 24 '20 at 10:37
  • 1
    It should return 29:30:00 – anduplats Apr 24 '20 at 10:44
  • So you remove all day references and the `% 24` from the hour calculation and you get what you expect right? If not could you explain better what result are you expecting for what input in more details? – acm Apr 24 '20 at 11:04
  • 1
    Ok, I've posted it as an answer so the answer doesn't get lost in a comment. – acm Apr 24 '20 at 11:11

1 Answers1

2

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);
    }
}
acm
  • 2,086
  • 3
  • 16
  • 34