Convert number of seconds to hour:minute:second format. - Java java.util

Java examples for java.util:Second

Description

Convert number of seconds to hour:minute:second format.

Demo Code


//package com.java2s;

public class Main {
    /**//  w ww .  j a  v a 2s.  c  om
     * Convert number of seconds to hour:minute:second format. Zeroes are added if appropriate.
     * E.G. secondToTime(72) returns "1:02"
     */
    public static String secondToTime(int seconds) {
        int reducedSeconds = seconds % 60;
        int minutes = seconds / 60;
        int reducedMinutes = minutes % 60;
        int hours = minutes / 60;
        if (hours == 0) {
            String secondsToString = (reducedSeconds >= 10) ? String
                    .valueOf(reducedSeconds) : "0" + reducedSeconds;
            return minutes + ":" + secondsToString;
        } else {
            String minutesToString = (reducedMinutes >= 10) ? String
                    .valueOf(reducedMinutes) : "0" + reducedMinutes;
            String secondsToString = (reducedSeconds >= 10) ? String
                    .valueOf(reducedSeconds) : "0" + reducedSeconds;
            return hours + ":" + minutesToString + ":" + secondsToString;
        }
    }
}

Related Tutorials