Java Time Format formatTimeAgo(int seconds)

Here you can find the source of formatTimeAgo(int seconds)

Description

Convert seconds into a human readable format.

License

Open Source License

Parameter

Parameter Description
seconds a parameter

Return

seconds.

Declaration

public static String formatTimeAgo(int seconds) 

Method Source Code

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

public class Main {
    /**/*from  w  w w . j ava2 s.  c  o  m*/
     * Convert seconds into a human readable format.
     *
     * @param seconds
     * @return seconds.
     */
    public static String formatTimeAgo(int seconds) {
        if (seconds == 0)
            return "0 seconds"; // @note: 0 seconds is a special case.

        String date = "";

        String[] unitNames = { "week", "day", "hour", "minute", "second" };
        int[] unitValues = { 604800, 86400, 3600, 60, 1 };

        // Loop through all of the units.
        for (int i = 0; i < unitNames.length; i++) {
            int quot = seconds / unitValues[i];
            if (quot > 0) {
                date += quot + " " + unitNames[i] + (Math.abs(quot) > 1 ? "s" : "") + ", ";
                seconds -= (quot * unitValues[i]);
            }
        }

        // Return the date, substring -2 to remove the trailing ", ".
        return date.substring(0, date.length() - 2);
    }

    /**
     * Convert milliseconds into a human readable format.
     *
     * @param milliseconds
     * @return String
     */
    public static String formatTimeAgo(Long milliseconds) {
        return formatTimeAgo((int) (milliseconds / 1000));
    }
}

Related

  1. formatTime(String timeStr)
  2. formatTime14To12String(String time)
  3. formatTime2(long secs)
  4. formatTime2(long timeInSeconds)
  5. formatTime3(long secs)
  6. formatTimeArea(Integer hour)
  7. formatTimeDeltaValue(long delta)
  8. formatTimeDiff(long finishTime, long startTime)
  9. formatTimeDiff(long finishTime, long startTime)