0

I want to differentiate between Current Date and Action Date. The difference should be shown as :

3 days ago 4 days ago and son ..

How can I achieve the same in Java using in Android?

It does not work for me and returns the actual date itself:

Date d = Utils.instanceDateFormat().parse(text.toString());
                String moments = DateUtils.getRelativeTimeSpanString(d.getTime(), new Date().getTime(), DateUtils.SECOND_IN_MILLIS,
                        DateUtils.FORMAT_ABBREV_ALL).toString();
codebased
  • 6,945
  • 9
  • 50
  • 84

3 Answers3

1

Try this

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String currentDateInput = "23 01 1997";
String actionDateInput = "27 04 1997";

try {
    Date currentDate = myFormat.parse(currentDateInput);
    Date actionDate = myFormat.parse(actionDateInput);
    long diff = actionDate.getTime() - currentDate.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

You will have to modify the SimpleDateFormat to fit your needs.

Marcus
  • 6,697
  • 11
  • 46
  • 89
1

Use this to get the difference between two date objects

public static int getDaysDifference(Date fromDate,Date toDate)
{
if(fromDate==null||toDate==null)
return 0;

return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
}
Fahim
  • 12,198
  • 5
  • 39
  • 57
0

I think you need to change the minimum resolution of SECONDS_IN_MILLIS to DAYS_IN_MILLIS like this ---> DateUtils.getRelativeTimeSpanString(date , System.currentTimeMillis(), DateUtils.DAYS_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString()

Using that all your future dates will be resolved to in X days and past dates to X days ago with exception of previous day which gets resolved to Yesterday but that would require a minor tweak if you need it to resolve to 1 day ago.

Hope this solves the issue

rahul.taicho
  • 1,339
  • 1
  • 8
  • 18