Java TimeUnit Usage formatDurationTill(long start)

Here you can find the source of formatDurationTill(long start)

Description

Calculate the duration between now and the given time Taken mostly from http://stackoverflow.com/a/5062810/207604 .

License

Apache License

Parameter

Parameter Description
start starting time (in milliseconds)

Return

time in seconds

Declaration

public static String formatDurationTill(long start) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

public class Main {
    /**// w  ww .jav a  2s .  c o  m
     * Calculate the duration between now and the given time
     *
     * Taken mostly from http://stackoverflow.com/a/5062810/207604 . Kudos to @dblevins
     *
     * @param start starting time (in milliseconds)
     * @return time in seconds
     *
     */
    public static String formatDurationTill(long start) {
        long duration = System.currentTimeMillis() - start;
        StringBuilder res = new StringBuilder();

        TimeUnit current = HOURS;

        while (duration > 0) {
            long temp = current.convert(duration, MILLISECONDS);

            if (temp > 0) {
                duration -= current.toMillis(temp);
                res.append(temp).append(" ").append(current.name().toLowerCase());
                if (temp < 2)
                    res.deleteCharAt(res.length() - 1);
                res.append(", ");
            }
            if (current == SECONDS) {
                break;
            }
            current = TimeUnit.values()[current.ordinal() - 1];
        }
        if (res.lastIndexOf(", ") < 0) {
            return duration + " " + MILLISECONDS.name().toLowerCase();
        }
        res.deleteCharAt(res.length() - 2);
        int i = res.lastIndexOf(", ");
        if (i > 0) {
            res.deleteCharAt(i);
            res.insert(i, " and");
        }

        return res.toString();
    }
}

Related

  1. formatDuration(long duration)
  2. formatDuration(long millis)
  3. formatDuration(long millis)
  4. formatDuration(long time)
  5. formatDurationSeconds(long seconds)
  6. formatElapsedSecs(long secs)
  7. formatElapsedTime(final long seconds)
  8. formatElapsedTime(long elapsedTimeMs)
  9. formatElapsedTime(long millis)