Java TimeUnit Usage formatTime(long time)

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

Description

Formats given time in hh:ss or HH:mm:ss format, depending on whether time is longer then hour or not.

License

Open Source License

Parameter

Parameter Description
time time in miliseconds

Return

formatted string

Declaration

public static String formatTime(long time) 

Method Source Code

//package com.java2s;

import java.util.concurrent.TimeUnit;

public class Main {
    /** Format string for displaying time without hours (e.g. 0:00) */
    private static final String FMT_NO_HR = "%d:%02d";
    /** Format string for displaying time with hours included (e.g. 0:00:00) */
    private static final String FMT_HR = "%d:%02d:%02d";

    /**//from  w w  w .jav  a 2 s  .c o m
     * Formats given time in hh:ss or HH:mm:ss format, depending on whether time is
     * longer then hour or not.
     * 
     * @param time time in miliseconds
     * @return formatted string
     */
    public static String formatTime(long time) {
        String result = null;
        long hr = TimeUnit.MILLISECONDS.toHours(time);
        long min = TimeUnit.MILLISECONDS.toMinutes(time
                - TimeUnit.HOURS.toMillis(hr));
        long sec = TimeUnit.MILLISECONDS.toSeconds(time
                - TimeUnit.HOURS.toMillis(hr)
                - TimeUnit.MINUTES.toMillis(min));
        if (hr == 0) {
            result = String.format(FMT_NO_HR, min, sec);
        } else {
            result = String.format(FMT_HR, hr, min, sec);
        }
        return result;
    }
}

Related

  1. formatMillis(long millis)
  2. formatMillisecs(long lMillisecs, final boolean bWantMSecs)
  3. formatMillisIntoMinutesAndSeconds(long millis)
  4. formatMs(long millis)
  5. formatSeconds(int seconds)
  6. formatTime(long time)
  7. formatTime(long timeInNanoseconds)
  8. formatTime(String format, double nanoseconds)
  9. formatTimeDuration(long duration)