Java Long Number Format format(long milliseconds)

Here you can find the source of format(long milliseconds)

Description

Only display the hours / minutes / seconds / milliseconds

License

Open Source License

Parameter

Parameter Description
milliseconds : elapsed time in milliseconds

Return

String formatted

Declaration

public static String format(long milliseconds) 

Method Source Code

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

public class Main {
    private static String format = String.format("%%0%dd", 2);

    /**// www  .  j  a v a  2 s  . co  m
     * Only display the hours / minutes / seconds / milliseconds 
     * 
     * @param milliseconds : elapsed time in milliseconds
     * 
     * @return String formatted
     */
    public static String format(long milliseconds) {

        StringBuilder buff = new StringBuilder();

        long elapsedTime = milliseconds / 1000;

        if (elapsedTime / 3600 > 0) {
            add(buff, String.format(format, elapsedTime / 3600), "h");
        }

        if ((elapsedTime % 3600) / 60 > 0) {
            add(buff, String.format(format, (elapsedTime % 3600) / 60), "m");
        }

        if ((elapsedTime % 60) > 0) {
            add(buff, String.format(format, elapsedTime % 60), "s");
        }

        if (milliseconds % 1000 > 0) {
            add(buff, String.format(format, milliseconds % 1000), "ms");
        }

        return buff.toString();
    }

    private static StringBuilder add(StringBuilder buff, String number, String scale) {
        if (buff.length() > 0) {
            buff.append(" ");
        }

        return buff.append(number).append(scale);
    }
}

Related

  1. format(final long number, final int length)
  2. format(final long value, final long divider, final String unit)
  3. format(final long value, final long divider, final String unit)
  4. format(long bytes)
  5. format(long mem)
  6. format(long ms)
  7. format(long numero, int numeroZeri)
  8. format(long offsetMillis)
  9. format(long s)