Java Time Format formatTime(long timeInMilli)

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

Description

Formats a time given in millisecond.

License

Open Source License

Parameter

Parameter Description
timeInMilli time in milli-seconds

Return

a String representing the formatted time...

Declaration

public static String formatTime(long timeInMilli) 

Method Source Code

//package com.java2s;

public class Main {
    /**// w w  w .  j  av a  2 s  . c o m
     * Formats a time given in millisecond. The output will be "X hours Y min Z sec", unless X, Y or Z is 0 in which
     * case that part of the string will be omitted.
     * <p/>
     * Created on May 3, 2004 by Fabian Depry
     * @param timeInMilli time in milli-seconds
     * @return a <code>String</code> representing the formatted time...
     */
    public static String formatTime(long timeInMilli) {
        long hourBasis = 60;

        StringBuilder formattedTime = new StringBuilder();

        long secTmp = timeInMilli / 1000;
        long sec = secTmp % hourBasis;
        long minTmp = secTmp / hourBasis;
        long min = minTmp % hourBasis;
        long hour = minTmp / hourBasis;

        if (hour > 0) {
            formattedTime.append(hour).append(" hour");
            if (hour > 1)
                formattedTime.append("s");
        }

        if (min > 0) {
            if (formattedTime.length() > 0)
                formattedTime.append(", ");
            formattedTime.append(min).append(" minute");
            if (min > 1)
                formattedTime.append("s");
        }

        if (sec > 0) {
            if (formattedTime.length() > 0)
                formattedTime.append(", ");
            formattedTime.append(sec).append(" second");
            if (sec > 1)
                formattedTime.append("s");
        }

        if (formattedTime.length() > 0)
            return formattedTime.toString();

        return "< 1 second";
    }
}

Related

  1. formatTime(long time)
  2. formatTime(long time, String syntax, boolean extraZeros)
  3. formatTime(long timeDiff)
  4. formatTime(long timeDiff)
  5. formatTime(long timeDiffMillis)
  6. formatTime(long timeInSecond)
  7. formatTime(long timeInterval, int maxTerms)
  8. formatTime(long timeMillis)
  9. formatTime(long value)