Java Duration Format formatDurationOneUnit(long milis)

Here you can find the source of formatDurationOneUnit(long milis)

Description

Formats length of time periods in a nice format

License

Apache License

Parameter

Parameter Description
milis a time difference in milliseconds to format

Return

formatted time (e.g.: "1 second", "3 hours", "2 weeks" "41 years"...)

Declaration

public static String formatDurationOneUnit(long milis) 

Method Source Code

//package com.java2s;
/*/*from   w  w w.ja  v a2 s  . c om*/
 * Copyright 2004-2010 Information & Software Engineering Group (188/1)
 *                     Institute of Software Technology and Interactive Systems
 *                     Vienna University of Technology, Austria
 *
 * 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.ifs.tuwien.ac.at/dm/somtoolbox/license.html
 *
 * 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.
 */

public class Main {
    /**
     * Formats length of time periods in a nice format
     * 
     * @param milis a time difference in milliseconds to format
     * @return formatted time (e.g.: "1 second", "3 hours", "2 weeks" "41 years"...)
     */
    public static String formatDurationOneUnit(long milis) {
        long secs = milis / 1000l;

        if (secs < 2l) {
            return "1 second";
        }
        if (secs == 2l) {
            return "2 seconds";
        }

        // default:
        long value = secs;
        String unit = "seconds";

        // now try to give it a meaning:
        long[] breaks = { 31536000, 2628000, 604800, 86400, 3600, 60, 1 };
        String[] desc = { "year", "month", "week", "day", "hour", "minute",
                "second" };

        int i = 0;
        while (i <= breaks.length && secs <= 2 * breaks[i]) {
            i++;
        }
        value = secs / breaks[i];
        unit = desc[i];
        if (value >= 2) {
            unit = unit + "s";
        }

        String retval = value + " " + unit;

        // if...
        return retval;
    }
}

Related

  1. formatDuration(long timeInMillis)
  2. formatDurationAsTime(final int duration)
  3. formatDurationHMSms(long ms)
  4. formatDurationLpad(final String s)
  5. formatDurationMills(long millis)
  6. formatHuman(Duration duration)
  7. formatISO8601Duration(int[] t)
  8. formatNanoDuration(final long nanos)
  9. formatPeriod(final Period period, final boolean wrapInDurationFunction)