Java Time Format formatTime(long time)

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

Description

Formats the given time to a string based on it's size.

License

Open Source License

Parameter

Parameter Description
time a parameter

Declaration

public static String formatTime(long time) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*  w w w .j  a v a2s.co  m*/
     * Formats the given <code>time</code> to a string based on it's size. If the size of the time is to larger it will
     * be push into the next time unit. ns -> us -> ms e.g.
     * 
     * <pre>
     *  1.) time = 123456789 nano seconds
     *  2.) time /= 1000
     *  3.) check if time is still to large and repeat second step
     *  return as string
     * </pre>
     * 
     * @param time
     * @return
     */
    public static String formatTime(long time) {
        int steps = 0;
        while (time >= 1000) {
            time /= 1000;
            steps++;
        }
        return time + getTimeUnit(steps);
    }

    private static String getTimeUnit(int steps) {
        switch (steps) {
        case 0:
            return "ns";
        case 1:
            return "us";
        case 2:
            return "ms";
        case 3:
            return "s";
        case 4:
            return "m";
        case 5:
            return "h";
        case 6:
            return "days";
        case 7:
            return "months";
        case 8:
            return "years";
        default:
            return "d (WTF dude check you calculation!)";
        }
    }
}

Related

  1. formatTime(long seconds)
  2. formatTime(long seconds)
  3. formatTime(long seconds)
  4. formatTime(long time)
  5. formatTime(long time)
  6. formatTime(long time)
  7. formatTime(long time)
  8. formatTime(long time)
  9. formatTime(long time)