Java Duration Format formatDuration(long millis)

Here you can find the source of formatDuration(long millis)

Description

Formats duration in user friendly format ex: 1d 32m 4ms

License

Open Source License

Parameter

Parameter Description
millis duration in milliseconds

Return

formated time

Declaration

public static String formatDuration(long millis) 

Method Source Code

//package com.java2s;

public class Main {
    private static final long SECOND_IN_MILLIS = 1000;
    private static final long MINUTE_IN_MILLIS = 60 * 1000;
    private static final long HOUR_IN_MILLIS = 60 * 60 * 1000;
    private static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;

    /**// w  w  w. j  a v  a  2 s.c  om
     * Formats duration in user friendly format ex: 1d 32m 4ms  
     * @param millis duration in milliseconds
     * @return formated time
     */
    public static String formatDuration(long millis) {
        long d = millis / DAY_IN_MILLIS;
        long h = (millis - d * DAY_IN_MILLIS) / HOUR_IN_MILLIS;
        long m = (millis - d * DAY_IN_MILLIS - h * HOUR_IN_MILLIS) / MINUTE_IN_MILLIS;
        long s = (millis - d * DAY_IN_MILLIS - h * HOUR_IN_MILLIS - m * MINUTE_IN_MILLIS) / SECOND_IN_MILLIS;
        long ms = millis % SECOND_IN_MILLIS;

        StringBuilder sb = new StringBuilder();
        appendTimePart(d, "d", sb);
        appendTimePart(h, "h", sb);
        appendTimePart(m, "m", sb);
        appendTimePart(s, "s", sb);
        appendTimePart(ms, "ms", sb);
        return sb.toString();
    }

    private static void appendTimePart(long time, String timeChar, StringBuilder sb) {
        if (time > 0) {
            if (sb.length() > 0) {
                sb.append(" ");
            }
            sb.append(time).append(timeChar);
        }
    }
}

Related

  1. formatDuration(long durationSec)
  2. formatDuration(long elapsed)
  3. formatDuration(long elapsedSec)
  4. formatDuration(Long input)
  5. formatDuration(long milis)
  6. formatDuration(long millis)
  7. formatDuration(long milliseconds)
  8. formatDuration(long milliseconds)
  9. formatDuration(long ms)