Android Date Interval Get timeDifference(Date date)

Here you can find the source of timeDifference(Date date)

Description

Returns the string representation of time difference based on today date.

Parameter

Parameter Description
date - Date object.

Exception

Parameter Description
NullPointerException if any of the parameters is null.

Return

- object.

Declaration

public static String timeDifference(Date date) 

Method Source Code

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;
    }
}

Related

  1. interval(Date date)
  2. checkIsIntervalDay(String startTime, String endTime)
  3. totalDays(Object o)
  4. calculatorDaysAgo(String date, Locale locale, String format)
  5. getFirstInterval(Context context, long lastupdate, long updateinterval)
  6. getTimeRangeStr(Date startDate, Date endDate)
  7. formatDuration(int duration)
  8. calcTimeBetween(Date start, Date end)
  9. getOffectDay(long date1, long date2)