Search code examples
androidandroid-dateutils

How can I obtain a relative time string with a three-letter month?


I am using this code to get a relative time in my app:

DateUtils.getRelativeTimeSpanString(
        mReferenceTime,
        now,
        DateUtils.MINUTE_IN_MILLIS,
        DateUtils.FORMAT_ABBREV_RELATIVE
);

It is returning everything correctly, but I want to shorten the month. For example, in place of "December 21" it should instead return "Dec 21". How can I achieve this?


Solution

  • Check out the flag DateUtils.FORMAT_ABBREV_MONTH. From the Android source code (lines 781-782):

    "If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated to a 3-letter string."

    Look at the three-parameter version of getRelativeTimeSpanString:

    public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) {
        int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH;
        return getRelativeTimeSpanString(time, now, minResolution, flags);
    }
    

    From this it would appear that passing in DateUtils.FORMAT_ABBREV_RELATIVE | DateUtils.FORMAT_ABBREV_MONTH as the fourth parameter to getRelativeTimeSpanString would solve your problem.