Java TimeUnit Usage getDurationBreakdown(long millis)

Here you can find the source of getDurationBreakdown(long millis)

Description

Convert a millisecond duration to a string format

License

Open Source License

Parameter

Parameter Description
millis A duration to convert to a string form

Return

A string of the form "X days Y hours Z minutes A seconds".

Declaration

public static String getDurationBreakdown(long millis) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.TimeUnit;

public class Main {
    /**/*from  ww w .j a va 2 s.co m*/
     * Convert a millisecond duration to a string format
     *
     * @param millis A duration to convert to a string form
     * @return A string of the form "X days Y hours Z minutes A seconds".
     */
    public static String getDurationBreakdown(long millis) {
        long ms = millis;
        if (ms < 0)
            return "ASAP";

        long days = TimeUnit.MILLISECONDS.toDays(ms);
        ms -= TimeUnit.DAYS.toMillis(days);
        long hours = TimeUnit.MILLISECONDS.toHours(ms);
        ms -= TimeUnit.HOURS.toMillis(hours);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(ms);
        ms -= TimeUnit.MINUTES.toMillis(minutes);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(ms);

        return getDurationString(days, hours, minutes, seconds);
    }

    private static String getDurationString(long days, long hours, long minutes, long seconds) {
        StringBuilder sb = new StringBuilder();
        if (days > 0) {
            sb.append(days);
            sb.append(" day");
            sb.append(days == 1 ? "" : "s");
            sb.append(" ");
        }

        if (days > 0 || hours > 0) {
            sb.append(hours);
            sb.append(" hour");
            sb.append(hours == 1 ? "" : "s");
            sb.append(" ");
        }

        if (days > 0 || hours > 0 || minutes > 0) {
            sb.append(minutes);
            sb.append(" minute");
            sb.append(minutes == 1 ? "" : "s");
            sb.append(" ");
        }

        sb.append(seconds);
        sb.append(" second");
        sb.append(seconds == 1 ? "" : "s");

        return sb.toString();
    }
}

Related

  1. getDeltaBetweenTimestamps(final long start, final long end)
  2. getDifferenceDays(Date d1, Date d2)
  3. getDiffInMinutes(Calendar startTime, Calendar endTime)
  4. getDurationBreakdown(long millis)
  5. getDurationBreakdown(long millis)
  6. getDurationBreakdown(long millis)
  7. getDurationBreakdown(long millis)
  8. getDurationFromMillis(long millis)
  9. getDurationFromMilliseconds(long duration)