Getting difference between two dates Android

Solution 1:

You can use getRelativeTimeSpanString(). It returns a string like "1 minute ago". Here is a real simple example that tells how long the application has been running.

private long mStartTime;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mStartTime = System.currentTimeMillis();
}

public void handleHowLongClick(View v) {
    CharSequence cs = DateUtils.getRelativeTimeSpanString(mStartTime);
    Toast.makeText(this, cs, Toast.LENGTH_LONG).show();
}

Solution 2:

Convert both dates into calender and make time 0(

today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);

).
Then use this fun :

public final static long SECOND_MILLIS = 1000;
public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
public final static long DAY_MILLIS = HOUR_MILLIS*24;

 public static int daysDiff( Date earlierDate, Date laterDate )
    {
        if( earlierDate == null || laterDate == null ) return 0;
        return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
    }

Solution 3:

Try the following method that I used in one of my applications:

/**
 * Returns difference between time and current time as string like:
 * "23 mins ago" relative to current time.
 * @param time - The time to compare with current time in yyyy-MM-dd HH:mm:ss format
 * @param currentTime - Present time in yyyy-MM-dd HH:mm:ss format
 * @return String - The time difference as relative text(e.g. 23 mins ago)
 * @throws ParseException
 */
private String getTimeDiff(String time, String currentTime) throws ParseException
{
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date currentDate = (Date)formatter.parse(currentTime);
    Date oldDate = (Date)formatter.parse(time);
    long oldMillis = oldDate.getTime();
    long currentMillis = currentDate.getTime();
    return DateUtils.getRelativeTimeSpanString(oldMillis, currentMillis, 0).toString();
}