Returns a formatted string with the duration in hours and minutes Example: "8 hours, 40 minutes" - Java java.util

Java examples for java.util:Minute

Description

Returns a formatted string with the duration in hours and minutes Example: "8 hours, 40 minutes"

Demo Code


//package com.java2s;
import java.util.Locale;

public class Main {
    /**/*from  w  ww  .j a va2 s  .c  om*/
     * Returns a formatted string with the duration in hours and minutes
     * Example: "8 hours, 40 minutes"
     * 
     * @param duration
     * @return
     */
    public static String durationToString(long duration) {

        int seconds = (int) ((duration / 1000) % 60);
        int minutes = (int) ((duration / (1000 * 60)) % 60);
        int hours = (int) ((duration / (1000 * 60 * 60)));
        String strHour = "hours";
        String strMin = "minutes";
        // The following is ugly, but needed...
        if (hours == 1) {
            strHour = "hour";
        }
        if (minutes == 1) {
            strMin = "minute";
        }
        String durationString = String.format(Locale.getDefault(),
                "%d %s, %d %s", hours, strHour, minutes, strMin);
        return durationString;
    }
}

Related Tutorials