Java TimeUnit Format formatMillis(long duration, TimeUnit max, TimeUnit min, boolean useAbbreviation)

Here you can find the source of formatMillis(long duration, TimeUnit max, TimeUnit min, boolean useAbbreviation)

Description

Converts time to a human readable format within the specified range http://stackoverflow.com/questions/3859288/how-to-calculate-time-ago-in-java

License

Open Source License

Parameter

Parameter Description
duration the time in milliseconds to be converted
max the highest time unit of interest
min the lowest time unit of interest

Declaration

public static String formatMillis(long duration, TimeUnit max, TimeUnit min, boolean useAbbreviation) 

Method Source Code


//package com.java2s;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class Main {
    /**/*from ww  w  .  j  av  a  2  s  . c om*/
     * Converts time to a human readable format within the specified range
     * http://stackoverflow.com/questions/3859288/how-to-calculate-time-ago-in-java
     * @param duration the time in milliseconds to be converted
     * @param max      the highest time unit of interest
     * @param min      the lowest time unit of interest
     */
    public static String formatMillis(long duration, TimeUnit max, TimeUnit min, boolean useAbbreviation) {
        StringBuilder res = new StringBuilder();

        TimeUnit current = max;

        while (duration > 0) {
            long temp = current.convert(duration, MILLISECONDS);

            if (temp > 0) {
                duration -= current.toMillis(temp);
                res.append(temp).append(" ").append(current.name().toLowerCase());
                if (temp < 2) {
                    res.deleteCharAt(res.length() - 1);
                }
                res.append(", ");
            }

            if (current == min) {
                break;
            }

            current = TimeUnit.values()[current.ordinal() - 1];
        }

        // clean up our formatting....

        // we never got a hit, the time is lower than we care about
        if (res.lastIndexOf(", ") < 0) {
            return "0 " + min.name().toLowerCase();
        }

        // yank trailing  ", "
        res.deleteCharAt(res.length() - 2);

        //  convert last ", " to " and"
        int i = res.lastIndexOf(", ");
        if (i > 0) {
            res.deleteCharAt(i);
            res.insert(i, " and");
        }

        if (useAbbreviation) {
            return res.toString().replace("minute", "min").replace("hour", "hr");
        } else {
            return res.toString();
        }
    }
}

Related

  1. format(final long duration, final TimeUnit sourceUnit, final TimeUnit min)
  2. formatDuration(long time, TimeUnit unit)
  3. formatHighest(long duration, final TimeUnit max)
  4. formatMinutesSeconds(final long sourceDuration, final TimeUnit sourceUnit)
  5. formatTime(long dt, TimeUnit input, TimeUnit output, int decimalPlaces)