Formats a given duration in seconds (e.g. - Java java.util

Java examples for java.util:Second

Description

Formats a given duration in seconds (e.g.

Demo Code


//package com.java2s;

public class Main {
    /**//from   w  w w  .  j  av a  2  s.c om
     * Formats a given duration in seconds (e.g. achieved by using a StopWatch)
     * as HH:MM:SS
     * 
     * @param seconds
     * @return
     */
    public static String formatDuration(long seconds) {
        String format = "";

        if (seconds <= 0L) {
            return "";
        }
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long secs = (seconds % 60);

        format += hours > 0 ? String.format("%02d", hours) + "h " : "";
        format += minutes > 0 ? String.format(hours > 0 ? "%02d" : "%d",
                minutes) + "m " : "";
        format += seconds > 0 ? String.format(minutes > 0 ? "%02d" : "%d",
                secs) + "s" : "";
        return format;
    }
}

Related Tutorials