Java TimeUnit Usage getDurationBreakdown(long millis)

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

Description

get Duration Breakdown

License

Apache License

Declaration

public static String getDurationBreakdown(long millis) 

Method Source Code

//package com.java2s;
/*//from   ww w.  j  av  a 2  s. c om
 * copyright (C) 2013 Christian P Rasmussen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.concurrent.TimeUnit;

public class Main {
    public static String getDurationBreakdown(long millis) {
        String[] units = { " Days ", " Hours ", " Minutes ", " Seconds " };
        Long[] values = new Long[units.length];
        if (millis < 0) {
            throw new IllegalArgumentException("Duration must be greater than zero!");
        }

        values[0] = TimeUnit.MILLISECONDS.toDays(millis);
        millis -= TimeUnit.DAYS.toMillis(values[0]);
        values[1] = TimeUnit.MILLISECONDS.toHours(millis);
        millis -= TimeUnit.HOURS.toMillis(values[1]);
        values[2] = TimeUnit.MILLISECONDS.toMinutes(millis);
        millis -= TimeUnit.MINUTES.toMillis(values[2]);
        values[3] = TimeUnit.MILLISECONDS.toSeconds(millis);

        StringBuilder sb = new StringBuilder(64);
        boolean startPrinting = false;
        for (int i = 0; i < units.length; i++) {
            if (!startPrinting && values[i] != 0)
                startPrinting = true;
            if (startPrinting) {
                sb.append(values[i]);
                sb.append(units[i]);
            }
        }

        return (sb.toString());
    }
}

Related

  1. getDays(final long ms)
  2. getDays(long endTs, Long lookback)
  3. getDeltaBetweenTimestamps(final long start, final long end)
  4. getDifferenceDays(Date d1, Date d2)
  5. getDiffInMinutes(Calendar startTime, Calendar endTime)
  6. getDurationBreakdown(long millis)
  7. getDurationBreakdown(long millis)
  8. getDurationBreakdown(long millis)
  9. getDurationBreakdown(long millis)