Java TimeUnit Calculate getIntervalInfo(long intervalDuration, TimeUnit unit)

Here you can find the source of getIntervalInfo(long intervalDuration, TimeUnit unit)

Description

get Interval Info

License

Apache License

Declaration

public static String getIntervalInfo(long intervalDuration, TimeUnit unit) 

Method Source Code


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

import java.util.concurrent.TimeUnit;

public class Main {
    public static String getIntervalInfo(long intervalDuration, TimeUnit unit) {
        TimeUnit[] timeUnits = TimeUnit.values();

        long[] values = new long[timeUnits.length];

        for (int i = 0; i < values.length; i++) {
            values[i] = (i == unit.ordinal()) ? intervalDuration : 0;
        }//w w w.  j ava 2s . c  o  m

        for (int i = 0; i < timeUnits.length - 1; i++) {
            long value = values[i];
            long nexUnitValue = timeUnits[i].convert(1, timeUnits[i + 1]);

            long nextUnitDelta = value / nexUnitValue;
            long remainder = value % nexUnitValue;

            values[i] = remainder;
            values[i + 1] = values[i + 1] + nextUnitDelta;
        }

        StringBuilder builder = new StringBuilder();

        for (int i = (timeUnits.length - 1); i >= 0; i--) {
            long valueTemp = values[i];
            TimeUnit unitTemp = timeUnits[i];

            if (valueTemp > 0) {
                if (builder.length() > 0) {
                    builder.append(", ");
                }
                builder.append(getValueString(valueTemp, unitTemp));
            }
        }

        if (builder.length() == 0) {
            builder.append(getValueString(intervalDuration, unit));
        }

        return builder.toString();
    }

    private static String getValueString(long value, TimeUnit unit) {
        String result = value + " " + unit.toString().toLowerCase();

        if (value == 1) {
            result = result.substring(0, result.length() - 1);
        }

        return result;
    }
}

Related

  1. getDifference(Calendar initDate, Calendar endDate, TimeUnit units)
  2. getExpiringMap(long time, TimeUnit unit)
  3. getFragment(final Calendar calendar, final int fragment, final TimeUnit unit)
  4. getFutureDate(long delay, TimeUnit timeUnit)
  5. getInterval(final Date startDate, final Date endDate, final TimeUnit timeUnit)
  6. getMilliseconds(int interval, TimeUnit unit)
  7. getNowTimeUnit(TimeUnit timeUnit)
  8. getParentUnit(TimeUnit unit)
  9. getProperUnitName(TimeUnit unit, long amount)