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!
You can use DateUtils.getRelativeTimeSpanString for that:
long now = System.currentTimeMillis(); DateUtils.getRelativeTimeSpanString(lastUpdated.getTime(), now, DateUtils.DAY_IN_MILLIS);
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 "...."; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With