Java Second Format formatSeconds(long millis)

Here you can find the source of formatSeconds(long millis)

Description

Formats the given long to X hour, Y min, Z sec.

License

LGPL

Parameter

Parameter Description
millis the time in milliseconds to format

Return

the formatted seconds

Declaration

public static String formatSeconds(long millis) 

Method Source Code

//package com.java2s;
/*//w ww . j  av a  2 s .c om
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

public class Main {
    /**
     * Number of milliseconds in a second.
     */
    public static final long MILLIS_PER_SECOND = 1000;
    /**
     * Number of milliseconds in a standard minute.
     */
    public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
    /**
     * Number of milliseconds in a standard hour.
     */
    public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
    /**
     * Number of milliseconds in a standard day.
     */
    public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;

    /**
     * Formats the given long to X hour, Y min, Z sec.
     * @param millis the time in milliseconds to format
     * @return the formatted seconds
     */
    public static String formatSeconds(long millis) {
        long[] values = new long[4];
        values[0] = millis / MILLIS_PER_DAY;
        values[1] = (millis / MILLIS_PER_HOUR) % 24;
        values[2] = (millis / MILLIS_PER_MINUTE) % 60;
        values[3] = (millis / MILLIS_PER_SECOND) % 60;

        String[] fields = { " d ", " h ", " min ", " sec" };

        StringBuffer buf = new StringBuffer(64);
        boolean valueOutput = false;

        for (int i = 0; i < 4; i++) {
            long value = values[i];

            if (value == 0) {
                if (valueOutput)
                    buf.append('0').append(fields[i]);
            } else {
                valueOutput = true;
                buf.append(value).append(fields[i]);
            }
        }

        return buf.toString().trim();
    }
}

Related

  1. formatSeconds(double value)
  2. formatSeconds(final int total)
  3. formatSeconds(int seconds)
  4. formatSeconds(int seconds)
  5. formatSeconds(long dSeconds, boolean exact)
  6. formatSeconds(long s, boolean letters)
  7. formatSeconds(long seconds)
  8. formatSeconds(long seconds)
  9. formatSeconds(long secsIn)