Java TimeUnit Usage formatDuration(long duration)

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

Description

format Duration

License

Apache License

Declaration

public static String formatDuration(long duration) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.concurrent.TimeUnit;

public class Main {
    public static String formatDuration(long duration) {

        long hours = TimeUnit.MILLISECONDS.toHours(duration);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) - (hours * 60);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) - (hours * 60 * 60) - (minutes * 60);
        long milliseconds = TimeUnit.MILLISECONDS.toMillis(duration) - (hours * 60 * 60 * 1000)
                - (minutes * 60 * 1000) - (seconds * 1000);

        StringBuilder builder = new StringBuilder();
        if (hours > 0) {
            builder.append(hours);// w ww.j  a va2 s  .  co  m
            builder.append("h, ");
        }
        if ((minutes > 0) || (builder.length() > 0)) {
            builder.append(minutes);
            builder.append("m, ");
        }
        if ((seconds > 0) || (builder.length() > 0)) {
            builder.append(seconds);
            builder.append("s, ");
        }
        if ((milliseconds > 0) || (builder.length() > 0)) {
            builder.append(milliseconds);
            builder.append("ms");
        }

        return builder.toString();
    }
}

Related

  1. durationToString(long millis)
  2. elapsedMicroSec(long startNanoTime)
  3. elapsedTime(long start, long end)
  4. elapsedTimeSince(Date d)
  5. format(long elapsed, boolean hours)
  6. formatDuration(long millis)
  7. formatDuration(long millis)
  8. formatDuration(long time)
  9. formatDurationSeconds(long seconds)