time Since, return string like ### days/minutes ago - Android java.util

Android examples for java.util:Minute

Description

time Since, return string like ### days/minutes ago

Demo Code


//package com.java2s;
import java.util.Date;

public class Main {
    public static String timeSince(long d1) {
        Date current = new Date();
        long diffInSeconds = (current.getTime() / 1000 - d1);

        long diff[] = new long[] { 0, 0, 0, 0 };
        /* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60
                : diffInSeconds);// ww w  . ja  va  2s .c  om
        long diffMins = diffInSeconds / 60;
        /* min */diff[2] = (diffMins >= 60 ? diffMins % 60 : diffMins);
        long diffHours = diffMins / 60;
        /* hours */diff[1] = (diffHours >= 24 ? diffHours % 24 : diffHours);
        long diffDays = diffHours / 24;
        /* days */diff[0] = diffDays;

        String output = "";
        if (diff[0] > 0)
            output = String.format("%d day%s ago", diff[0],
                    diff[0] > 1 ? "s" : "");
        else if (diff[1] > 0)
            output = String.format("%d hour%s ago", diff[1],
                    diff[1] > 1 ? "s" : "");
        else if (diff[2] > 0)
            output = String.format("%d minute%s ago", diff[2],
                    diff[2] > 1 ? "s" : "");
        else
            output = String.format("%d second%s ago", diff[3],
                    diff[3] > 1 ? "s" : "");
        return output;

        /*
        return (String.format(
            "%d day%s, %d hour%s, %d minute%s, %d second%s ago",
            diff[0],
            diff[0] > 1 ? "s" : "",
            diff[1],
            diff[1] > 1 ? "s" : "",
            diff[2],
            diff[2] > 1 ? "s" : "",
            diff[3],
            diff[3] > 1 ? "s" : ""));
         */
    }
}

Related Tutorials