Convert long value time Elapsed To String - Java java.util

Java examples for java.util:Time Format

Description

Convert long value time Elapsed To String

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        long time = 42;
        System.out.println(timeElapsedToString(time));
    }/* w w w.  ja  v a2s  .c  o m*/

    public static final long ONE_WEEK_IN_MILISECONDS = 604800000L;
    public static final long ONE_DAY_IN_MILISECONDS = 86400000L;
    public static final long ONE_HOUR_IN_MILISECONDS = 3600000L;
    public static final long ONE_MINUTE_IN_MILISECONDS = 60000L;
    public static final long ONE_SECOND_IN_MILISECONDS = 1000L;

    /**
     *
     * @param time
     * @return
     */
    public static String timeElapsedToString(long time) {
        String returnTime = "";
        long temp;

        if (time / ONE_WEEK_IN_MILISECONDS > 0) {
            temp = time / ONE_WEEK_IN_MILISECONDS;
            String week = (temp > 1) ? temp + " weeks " : temp + " week ";
            returnTime += week + " ago";

        } else if (time / ONE_DAY_IN_MILISECONDS > 0) {
            temp = time / ONE_DAY_IN_MILISECONDS;
            String day = (temp > 1) ? temp + " days " : temp + " day ";
            returnTime += day + "ago";

        } else if (time / ONE_HOUR_IN_MILISECONDS > 0) {
            temp = time / ONE_HOUR_IN_MILISECONDS;
            String hour = (temp > 1) ? temp + " hours " : temp + " hour ";
            returnTime += hour + "ago";

        } else if (time / ONE_MINUTE_IN_MILISECONDS > 0) {
            temp = time / ONE_MINUTE_IN_MILISECONDS;
            String minute = (temp > 1) ? temp + " minutes " : temp
                    + " minute ";
            returnTime += minute + "ago";

        } else if (time / ONE_SECOND_IN_MILISECONDS > 0) {
            temp = time / ONE_SECOND_IN_MILISECONDS;
            String second = (temp > 1) ? temp + " seconds " : temp
                    + " second ";
            returnTime += second + "ago";
        } else {
            returnTime = "Just now";
        }
        return returnTime;
    }
}

Related Tutorials