Search code examples
androidandroid-datedateandroid-dateutilsapache-commons-dateutils

DateUtils.getRelativeTimeSpanString Returning a Formatted Date String Instead of "Hours/Minutes Ago"


I'm having fierce problems trying to get DateUtils.getRelativeTimeSpanString to return what it's supposed to in Android.

I've been through every similar question here and none of the solutions posted are working or relevant.

Here's my code:

CharSequence relativeDate = 
DateUtils.getRelativeTimeSpanString(System.currentTimeMillis(), 
            currentNewsItem.getTimeInMilliseconds(), 
            DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);
            dateView.setText(relativeDate);

The currentNewsItem.getTimeInMilliseconds method does indeed return a long (for example, just now it passed 1521759734 which seems correct) and the getRelativeTimeSpanString passes a correctly formatted date string to the view in the format "March 23, 2018" so it knows the correct date. But I need it to pass "x Hours ago" or "x minutes ago" and I cannot for the life of me figure out why it's not.

I've checked the time on the emulator, and the problem occurs on my device so it's not the timezone settings.

Documentation says that it will revert to a date string like this if the time span is greater than 7 days but I've checked the long that's being passed as the old time and the converter websites shows it's the exact time 4 hours ago. Besides, it's showing the correct date (today), just not the hours/minutes ago.

I've tried the HOUR_IN_MILLIS, MINUTES_IN_MILLIS and SECONDS_IN_MILLIS constants for the third parameter and I've tried removing the last abbreviation parameter and it's still the same result.

I've tried the various public method signatures to try find one that might work but they all have the same result.

Has anyone experienced this or can anyone point out where I'm going wrong? Many thanks.


Solution

  • If you check DateUtils.getRelativeTimeSpanString, the parameters are listed as:

    getRelativeTimeSpanString (long time, 
                long now, 
                long minResolution, 
                int flags)
    

    However in your code,
    now: the current time in milliseconds, is passed as 1st parameter instead of currentNewsItem.getTimeInMilliseconds().

    To get relative timespan like X minutes ago you can use DateUtils.MINUTE_IN_MILLIS and flag like DateUtils.FORMAT_ABBREV_RELATIVE will abbreviate relative time as X mins. ago.

    So, you can change your code to:

    CharSequence relativeDate = 
    DateUtils.getRelativeTimeSpanString(currentNewsItem.getTimeInMilliseconds(), 
            System.currentTimeMillis(),
            DateUtils.MINUTE_IN_MILLIS,
            DateUtils.FORMAT_ABBREV_RELATIVE);
    dateView.setText(relativeDate);