Java TimeUnit Format formatHighest(long duration, final TimeUnit max)

Here you can find the source of formatHighest(long duration, final TimeUnit max)

Description

Converts time to a human readable format within the specified range

License

Apache License

Parameter

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

Declaration

public static String formatHighest(long duration, final TimeUnit max) 

Method Source Code

//package com.java2s;
/**/*w w  w . jav a2s. c o m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 {
    /**
     * Converts time to a human readable format within the specified range
     *
     * @param duration the time in milliseconds to be converted
     * @param max      the highest time unit of interest
     */
    public static String formatHighest(long duration, final TimeUnit max) {
        final TimeUnit[] units = TimeUnit.values();

        final StringBuilder res = new StringBuilder();

        TimeUnit current = max;

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

            if (temp > 0) {

                duration -= current.toMillis(temp);

                res.append(temp).append(" ").append(current.name().toLowerCase());

                if (temp < 2) {
                    res.deleteCharAt(res.length() - 1);
                }

                break;
            }

            if (current == TimeUnit.MILLISECONDS) {
                break;
            }

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

        // we never got a hit, the time is lower than we care about
        return res.toString();
    }
}

Related

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