Java TimeUnit Calculate humanReadableTime(long time, TimeUnit unit)

Here you can find the source of humanReadableTime(long time, TimeUnit unit)

Description

Convert the given time to a human readable string representation.

License

Open Source License

Parameter

Parameter Description
time time convert
unit a parameter

Declaration

public static String humanReadableTime(long time, TimeUnit unit) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;

public class Main {
    private static final TimeUnit[] TIME_UNITS = new TimeUnit[] { DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS,
            MICROSECONDS };/*from w  w  w  .j av a2s.c  o m*/

    /**
     * Convert the given time to a human readable string representation.
     *
     * @param time time convert
     * @param unit
     * @return
     */
    public static String humanReadableTime(long time, TimeUnit unit) {
        final TimeUnit unit1 = largestNonzeroUnit(time, unit);

        final long value1 = time / unit.convert(1, unit1);
        final long timeRemainder = time % unit.convert(1, unit1);

        if (unit1 == NANOSECONDS || timeRemainder == 0) {
            return String.format("%d %s", value1, unit1.name().toLowerCase());
        } else {
            final TimeUnit unit2 = largestNonzeroUnit(timeRemainder, unit);
            final long value2 = timeRemainder / unit.convert(1, unit2);

            return String.format("%d %s %d %s", value1, unit1.name().toLowerCase(), value2,
                    unit2.name().toLowerCase());
        }
    }

    private static TimeUnit largestNonzeroUnit(final long time, final TimeUnit unit) {
        for (final TimeUnit newUnit : TIME_UNITS)
            if (newUnit.convert(time, unit) > 0)
                return newUnit;
        return NANOSECONDS;
    }
}

Related

  1. getTimeUnit(Object units)
  2. getTimeUnit(String timeUnit, TimeUnit defaultUnit)
  3. getTimeUnitByName(String timeUnit, TimeUnit defaultTimeUnit)
  4. getValueString(long value, TimeUnit unit)
  5. getWindowFlooredBinaryTime(TimeUnit unit, long timestamp, int windowSizeInSeconds)
  6. isValidTimeUnit(String timeUnit)
  7. logTiming(String description, int n, long time, TimeUnit unit)
  8. mapByName(TimeUnit... units)
  9. minus(Date date, int interval, TimeUnit unit)