Format relative date to human readable format in Android using Android DateUtils API

Loc picture Loc · Sep 12, 2014 · Viewed 17.3k times · Source

I have a date field ( lastUpdated ). I want to translate this date to human readable format such as 'today', '1 day ago', '2 days ago', ...

I am using android.text.format.DateUtils API that included in Android library.

Here is my try:

 DateUtils.getRelativeDateTimeString(context, 
                  lastUpdated.getTime(), 
                  DateUtils.DAY_IN_MILLIS, 
                  DateUtils.WEEK_IN_MILLIS, 
                  DateUtils.FORMAT_SHOW_YEAR);

Here is the output:

0 day ago, 12:00am
yesterday, 9:30am
2 days ago, 1:30pm
Sep 4, 12:30pm

The result I expected: ( No time information )

0 day ago --------- This should be 'today'
yesterday
2 days ago
Sep 4

NOTE that, if I clear time from lastUpdated. It will show '12:00am' for time information.

Anyone has any ideas? Is there any way to remove time from output?

Thank you!

Answer

Idolon picture Idolon · Sep 12, 2014

You can use DateUtils.getRelativeTimeSpanString for that:

long now = System.currentTimeMillis();
DateUtils.getRelativeTimeSpanString(lastUpdated.getTime(), now, DateUtils.DAY_IN_MILLIS);