Search code examples
javaandroidandroid-dateutils

Display relative date with custom format in Android


I want to translate a date to human readable format. I am using DateUtils. getRelativeDateTimeString, but this does not fit the criteria. The output I am getting looks like: 1 hour, 15 min. ago, etc.

I want to know if it is possible to change the format to:

3m instead of 3 min. ago,

1h instead of 1 hour. 15 min. ago etc.

using DateUtils or is there another way to do this?

To be more precise I am looking for an Android equivalent of this angular-filter where you can easily change the format of the relative date (for example: {{minutes}} minutes ago to {{minutes}}m.

To make myself clear, I am not searching for a way to format a date, but to translate a date to human readable format such as 'today', '1 hr', '38 min' (simillar to facebook's relative dates).


Solution

  • After some research, I found out some libraries like Time4A, Joda-Time, PrettyTime, Android-Ago.

    However, I have decided not to use a library and override its text resources, but to create a method and store text in strings.xml for possible future localization.

        private static final int SECOND_MILLIS = 1000;
        private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
        private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
        private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
        private static final int WEEK_MILLIS = 7 * DAY_MILLIS;
    
        public static String getTimeAgo(Date date, Context context) {
            Date now = Calendar.getInstance().getTime();
            final long diff = now.getTime() - date.getTime();
    
            if (diff < SECOND_MILLIS) {
                return context.getString(R.string.just_now);
            } else if (diff < MINUTE_MILLIS) {
                return diff / SECOND_MILLIS + context.getString(R.string.seconds_ago);
            } else if (diff < 2 * MINUTE_MILLIS) {
                return context.getString(R.string.a_minute_ago);
            } else if (diff < 59 * MINUTE_MILLIS) {
                return diff / MINUTE_MILLIS + context.getString(R.string.minutes_ago);
            } else if (diff < 90 * MINUTE_MILLIS) {
                return context.getString(R.string.an_hour_ago);
            } else if (diff < 24 * HOUR_MILLIS) {
                return diff / HOUR_MILLIS + context.getString(R.string.hours_ago);
            } else if (diff < 48 * HOUR_MILLIS) {
                return context.getString(R.string.yesterday);
            } else if (diff < 6 * DAY_MILLIS) {
                return diff / DAY_MILLIS + context.getString(R.string.days_ago);
            } else if (diff < 11 * DAY_MILLIS) {
                return context.getString(R.string.a_week_ago);
            } else {
                return diff / WEEK_MILLIS + context.getString(R.string.weeks_ago);
            }
        }