Java TimeUnit Usage humanReadableDuration(Date from, Date to)

Here you can find the source of humanReadableDuration(Date from, Date to)

Description

Prints time duration in pretty form.

License

Open Source License

Parameter

Parameter Description
from start of duration
to end of duration

Return

Pretty string representation of the duration

Declaration

public static String humanReadableDuration(Date from, Date to) 

Method Source Code


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

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {
    /**//from  w  w  w .jav  a2  s .  c o  m
     * Prints time duration in pretty form. Example: {@code 1h 5m 14s 124ms}
     *
     * @param from start of duration
     * @param to end of duration
     * @return Pretty string representation of the duration
     */
    public static String humanReadableDuration(Date from, Date to) {
        StringBuilder sb = new StringBuilder();
        if (from == null) {
            return "";
        }
        if (to == null) {
            return "";
        }
        long millis = to.getTime() - from.getTime();

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

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

        long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
        millis = millis - TimeUnit.SECONDS.toMillis(seconds);

        if (hours != 0) {
            sb.append(hours).append("h ");
        }
        if (minutes != 0) {
            sb.append(minutes).append("m ");
        }
        if (seconds != 0) {
            sb.append(seconds).append("s ");
        }
        if (millis != 0) {
            sb.append(millis).append("ms ");
        }
        return sb.toString();
    }
}

Related

  1. getUnit(long nanos)
  2. getValidityAsString(Date endDate)
  3. getWithTimeout(final Future future)
  4. humanizeTime(long hours, long minutes, long seconds)
  5. humanizeToTime(long millis)
  6. humanReadableMillis(long millis)
  7. isCurrentDateBeforeAndWithinRangeOfDate( Date date, int rangeInDays)
  8. isTheSameDayCheckSummerTime(final Date day1, final Date day2, final boolean escapeYear)
  9. isTimedOut(long start, long timeout)