Here you can find the source of timeDifference(Date date)
Parameter | Description |
---|---|
date | - Date object. |
Parameter | Description |
---|---|
NullPointerException | if any of the parameters is null. |
public static String timeDifference(Date date)
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main{ /**// w w w . j a v a2 s. com * Returns the string representation of time difference based on today date. * * @param date -{@link Date} object. * @return -{@link String} object. * @throws NullPointerException if any of the parameters is null. */ public static String timeDifference(Date date) { if (StringUtils.isNull(date)) { throw new NullPointerException("date cannot be null"); } String returnTimediff; Date nowdate = new Date(); int diffInDays = (int) ((nowdate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); int diffInHours = (int) ((nowdate.getTime() - date.getTime()) / (1000 * 60 * 60)) % 24; int diffInMins = (int) ((nowdate.getTime() - date.getTime()) / (1000 * 60)) % 60; // int diffInSec = (int) ((nowdate.getTime() - date.getTime()) / (1000 ))%60; if ((diffInDays >= 1) && (diffInDays < 2)) { returnTimediff = " yesterday"; } else if (diffInDays >= 2) { returnTimediff = diffInDays + " days ago"; } else if ((diffInHours < 24) && (diffInHours >= 1)) { returnTimediff = "" + diffInHours + " hours ago"; } else if ((diffInMins < 60) && (diffInMins > 1)) { returnTimediff = "" + diffInMins + " minutes ago"; } else { returnTimediff = "few seconds ago"; } return returnTimediff; } }