Java tutorial
//package com.java2s; import android.util.Log; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.concurrent.TimeUnit; public class Main { private static int counter = 0; /** * Gets a long value i.e the time when the call was made and then returns a * appropriate string * * @param callDate a long value which represents the time when the call was made * @return a formatted string to be displayed. */ public static String getTheTimePassedSinceCall(long callDate) { long difference = System.currentTimeMillis() - callDate; long diffInSeconds = getDateDiff(difference, TimeUnit.SECONDS); long diffInMin = getDateDiff(difference, TimeUnit.MINUTES); long diffInHours = getDateDiff(difference, TimeUnit.HOURS); return getDifferenceString(diffInSeconds, diffInMin, diffInHours, callDate); } /** * Get a diff between two dates * * @param timeUnit the unit in which you want the diff * @return the diff value, in the provided unit */ private static long getDateDiff(long diffInMillis, TimeUnit timeUnit) { return timeUnit.convert(diffInMillis, TimeUnit.MILLISECONDS); } /** * gets a diff types of representation of the current time and * converts it into a proper form. * * @param diffInSeconds difference between current date and call date in seconds. * @param diffInMin difference between current date and call date in minutes. * @param diffInHours difference between current date and call date in hours. * @param callDate the exact date time when call was made. * @return a string representation of the time. */ private static String getDifferenceString(long diffInSeconds, long diffInMin, long diffInHours, long callDate) { Log.v("Utility class", "counter: " + ++counter + "sec: " + diffInSeconds + "min: " + diffInMin + "hour: " + diffInHours + "call_date: " + callDate); //Getting the time in minuets and seconds since the time passed. if (diffInSeconds > 60) diffInSeconds = diffInSeconds % 60; if (diffInMin > 60) diffInMin = diffInMin % 60; //Formatting the string to be returned. if (diffInMin <= 5 && diffInHours == 0) return diffInMin + "m " + diffInSeconds + "s ago"; else if (diffInMin > 5 && diffInHours == 0) return diffInMin + "m ago"; else if (diffInHours <= 5) return diffInHours + "h " + diffInMin + "m ago"; else if (diffInHours > 5 && diffInHours <= 24) return diffInHours + " hours ago"; else if (diffInHours > 24 && diffInHours <= 168) return diffInHours / 24 + " days ago"; else { Date calledDate = new Date(callDate); return new SimpleDateFormat("MMM d, EEE", Locale.ENGLISH).format(calledDate); } } }