Returns elapsed time formatted as 000d 00h 00m 00s. - Java java.util

Java examples for java.util:Time Format

Description

Returns elapsed time formatted as 000d 00h 00m 00s.

Demo Code


//package com.java2s;
import java.text.DecimalFormat;

public class Main {
    /** // ww  w.ja  v  a  2s .c  o m
     * Returns elapsed time formatted as 000d 00h 00m 00s. 
     */
    public static final String formatElapsedTime(long time) {
        StringBuffer sb = new StringBuffer();

        if (time < 0) {
            sb.append("-");
            time = -time;
        }
        DecimalFormat tdf = new DecimalFormat("00");

        DecimalFormat msecf = new DecimalFormat(".000");
        // time is in millis
        // output format should be: 000d 00h 00:00

        if (time == 0)
            return "00m 00s";

        double seconds = (double) ((double) time / (double) 1000.0);

        double msec = seconds - Math.floor(seconds);

        int days = (int) Math.floor(seconds / (double) (24 * 60 * 60));
        seconds = seconds - ((double) days * (double) (24 * 60 * 60));

        int hours = (int) Math.floor(seconds / (double) (60 * 60));
        seconds = seconds - ((double) hours * (double) (60 * 60));

        int minutes = (int) Math.floor(seconds / (double) 60);
        seconds = seconds - ((double) minutes * (double) 60);

        if (days > 0)
            sb.append(tdf.format(days) + "d ");
        if (hours > 0)
            sb.append(tdf.format(hours) + "h ");

        if (minutes > 0)
            sb.append(tdf.format(minutes) + "m ");

        sb.append(tdf.format(seconds) + msecf.format(msec) + "s");

        return sb.toString();
    }
}

Related Tutorials