Java Time Format formatTime(long elapsedTime)

Here you can find the source of formatTime(long elapsedTime)

Description

Formats a long value denoting a time interval into a more readable String .

License

Open Source License

Parameter

Parameter Description
elapsedTime a long denoting a time interval in milliseconds.

Return

a describing the interval in terms of hours, minutes, seconds and milliseconds.

Declaration

public static String formatTime(long elapsedTime) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Milliseconds in one second */
    private static final long ONE_SEC = 1000;
    /** Milliseconds in one minute */
    private static final long ONE_MIN = ONE_SEC * 60;
    /** Milliseconds in one hour */
    private static final long ONE_HOUR = ONE_MIN * 60;

    /**/*  w w w  . ja v  a  2  s  .  c o m*/
     * Formats a {@code long} value denoting a time interval into a more
     * readable {@link String}.
     * 
     * @param elapsedTime
     *            a {@code long} denoting a time interval in milliseconds.
     * @return a {@link String} describing the interval in terms of hours,
     *         minutes, seconds and milliseconds.
     */
    public static String formatTime(long elapsedTime) {
        final long millisToPrint = ((elapsedTime % ONE_HOUR) % ONE_MIN) % ONE_SEC;
        final long secondsToPrint = ((elapsedTime % ONE_HOUR) % ONE_MIN) / ONE_SEC;
        final long minutesToPrint = (elapsedTime % ONE_HOUR) / ONE_MIN;
        final long hoursToPrint = elapsedTime / ONE_HOUR;

        String result = null;
        if (hoursToPrint > 0) {
            result = hoursToPrint + " hr";
        }
        if (minutesToPrint > 0) {
            result = (result == null ? "" : (result + " ")) + minutesToPrint + " min";
        }
        if (secondsToPrint > 0) {
            result = (result == null ? "" : (result + " ")) + secondsToPrint + " sec";
        }
        result = (result == null ? "" : (result + " ")) + millisToPrint + " msec";
        return result;
    }
}

Related

  1. formatTime(int value)
  2. formatTime(Integer hour, Integer minute, Integer second, Integer ampm, Integer zoneOffset)
  3. formatTime(Integer seconds)
  4. formatTime(long dtNanos)
  5. formatTime(long elapsedTime)
  6. formatTime(long millis)
  7. formatTime(long millis)
  8. formatTime(long millis)
  9. formatTime(long millis)