Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 791
Loc Avatar asked Sep 12 '14 16:09

Loc


2 Answers

You can use DateUtils.getRelativeTimeSpanString for that:

long now = System.currentTimeMillis(); DateUtils.getRelativeTimeSpanString(lastUpdated.getTime(), now, DateUtils.DAY_IN_MILLIS); 
like image 192
Idolon Avatar answered Sep 22 '22 22:09

Idolon


it seems like you want to have a custom handler for the times that are recent, and something more stdnard for dates that are further away. something like this would work:

public String getTimeDiff(long secondsTimeDiff) {            long secondsInOneDay = 84600;     int maxDaysAgo = 10;      if ( secondsTimeDiff < secondsInOneDay)     {         return "today";     }     else if ( secondsTimeDiff < 2*secondsInOneDay)     {         return "yesterday";     }     else if ( secondsTimeDiff < maxDaysAgo*secondsInOneDay)     {         int days = (int) (secondsTimeDiff / secondsInOneDay);         return days + " days ago";     }     else     {         //use normal DateUtils logic here...         return "....";     } } 
like image 33
Dave Avatar answered Sep 24 '22 22:09

Dave