Java TimeUnit Usage getTimeString(long millis)

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

Description

Formats milliseconds into human readable text.

License

Open Source License

Parameter

Parameter Description
millis Milliseconds to be formatted.

Return

The formatted string that looks beautiful.

Declaration

public static String getTimeString(long millis) 

Method Source Code

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

import java.util.concurrent.TimeUnit;

public class Main {
    /**//from www .  j a  va  2  s. c  om
     * Formats milliseconds into human readable text.
     *
     * @param millis Milliseconds to be formatted.
     * @return The formatted string that looks beautiful.
     */
    public static String getTimeString(long millis) {

        if (millis < 1L) {
            return "not very long!";
        } else {
            long days = TimeUnit.MILLISECONDS.toDays(millis);

            millis -= TimeUnit.DAYS.toMillis(days);
            long hours = TimeUnit.MILLISECONDS.toHours(millis);

            millis -= TimeUnit.HOURS.toMillis(hours);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);

            millis -= TimeUnit.MINUTES.toMillis(minutes);
            long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
            StringBuilder sb = new StringBuilder();

            if (days > 0L) {
                sb.append(days).append(" day");
                if (days > 1L) {
                    sb.append("s");
                }
            }

            if (hours > 0L) {
                if (days > 0L) {
                    sb.append(", ");
                }

                sb.append(hours).append(" hour");
                if (hours > 1L) {
                    sb.append("s");
                }
            }

            if (minutes > 0L) {
                if (hours > 0L || days > 0L) {
                    sb.append(", ");
                }

                sb.append(minutes).append(" minute");
                if (minutes > 1L) {
                    sb.append("s");
                }
            }

            if (seconds > 0L) {
                if (minutes > 0L || hours > 0L || days > 0L) {
                    sb.append(", ");
                }

                sb.append(seconds).append(" second");
                if (seconds > 1L) {
                    sb.append("s");
                }
            }

            return sb.toString();
        }

    }
}

Related

  1. getTimeComparisonEpsilonMicros()
  2. getTimeDifference(Date startDate, Date endDate)
  3. getTimeFormat(final long time)
  4. getTimeForS3URL()
  5. getTimeInMillis(String str)
  6. getTimezoneOffset(TimeZone timeZone)
  7. getTomorrowTimestamp()
  8. getUnit(long nanos)
  9. getValidityAsString(Date endDate)