Java Duration Format formatDuration(long milis)

Here you can find the source of formatDuration(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.: "3 hours, 2 minutes, 5 seconds")

Declaration

public static String formatDuration(long milis) 

Method Source Code

//package com.java2s;
/*//from   www  . j a  v  a2s. 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.: "3 hours, 2 minutes, 5 seconds")
     */
    public static String formatDuration(long milis) {
        // special formatting for times under 10 second
        if (milis < 10 * 1000) {
            return milis / 10 / 100.0 + " seconds";
        }
        long seconds = milis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        String result = "";
        if (hours > 0) {
            result += hours;
            if (hours == 1) {
                result += " hour, ";
            } else {
                result += " hours, ";
            }
            minutes = minutes - hours * 60;
            seconds = seconds - hours * 60 * 60;
        }
        if (minutes > 0) {
            result += minutes;
            if (minutes == 1) {
                result += " minute, ";
            } else {
                result += " minutes, ";
            }
            seconds = seconds - minutes * 60;
        }
        result += seconds;
        if (seconds == 1) {
            result += " second";
        } else {
            result += " seconds";
        }
        return result;
    }
}

Related

  1. formatDuration(long durationMillis)
  2. formatDuration(long durationSec)
  3. formatDuration(long elapsed)
  4. formatDuration(long elapsedSec)
  5. formatDuration(Long input)
  6. formatDuration(long millis)
  7. formatDuration(long millis)
  8. formatDuration(long milliseconds)
  9. formatDuration(long milliseconds)