0

is there any way to shorten this code? In the code, times of microseconds are converted into minutes and seconds. For example 305862000 ms = 05:05 (5 min : 5 sec).

public static String timeFormatter (long microtime) {
    String time = null, timemin = null, timesec = null;
    long min = 0;
    long sec = 0;

    // check if time is negative
    if (microtime < 0) {
        throw new RuntimeException("Negativ time value provided");
    } else {
        min = (long) (microtime/(Math.pow((double) 10,(double) 6))/60);
        if (min < 10) {
            timemin = "0" + min;
        // check if time is too long
        } else if (min > 99) {
            throw new RuntimeException("Time value exceeds allowed format");
        } else {
            timemin = min + "";
        }
        microtime = (long) (microtime - min*60*Math.pow((double) 10, (double) 6));
        sec = (long) (microtime/Math.pow(10, 6));
        if (sec < 10) {
            timesec = "0" + sec;
        } else {
            timesec = sec + "";
        }
        time = timemin + ":" + timesec;
    }
    return time;
}
Daniel
  • 13
  • 2
  • FYI: `ms` is **milli**-second. **Micro**-second is abbreviated as `μs`. See [List of SI prefixes](https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes). – Andreas May 12 '20 at 18:42

2 Answers2

5

Calculation

long milliseconds = microtime/1000;
Duration durationInMilliseconds = Duration.ofMillis(milliseconds);

Formatting

Using Apache Common DurationFormatUtils: https://github.com/apache/commons-lang

boolean padWithZeros = true;
DurationFormatUtils.formatDuration(millis, "**mm:ss**", padWithZeros);

Without a library (from Zabuzard's comment), see:

How to format a duration in java? (e.g format H:MM:SS)

Community
  • 1
  • 1
Tom Cools
  • 1,098
  • 8
  • 23
1

Use String.format() to format numbers with leading zeroes.

public static String timeFormatter(long microtime) {
    if (microtime < 0)
        throw new IllegalArgumentException("Negative time value provided: " + microtime);
    if (microtime >= 6000000000L/*100 mins*/)
        throw new IllegalArgumentException("Time value exceeds allowed format: " + microtime);
    long seconds = microtime / 1000000;
    return String.format("%02d:%02d", seconds / 60, seconds % 60);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247