androidandroid-dateutilsrelative-time-span

getRelativeDateTimeString with day of week?


Is there any option to get getRelativeDateTimeString in day of week. Means if the date is within 7 days show it as Mon, 7:14am instead of 4 days ago, 7:14 am

DateUtils.getRelativeDateTimeString(context,
            datewithTime.getTime(), DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0)

Solution

  • Hi you can use like this,

    public class TimeUtils extends android.text.format.DateUtils {
    
        private static boolean isWithinWeek(final long millis) {
            return System.currentTimeMillis() - millis <= (WEEK_IN_MILLIS - DAY_IN_MILLIS);
        }
    
        private static boolean isWithinYear(final long millis) {
            return System.currentTimeMillis() - millis <= YEAR_IN_MILLIS;
        }
    
        public static String getRelativeTimeSpanString(final Context c, final long millis) {
            final String dateString;
            if (isToday(millis)) {
                dateString = formatDate(millis, "h:mm:ss a");
                // dateString = DateUtils.formatDateTime(c, millis, DateUtils.FORMAT_SHOW_TIME
                // | DateUtils.FORMAT_ABBREV_TIME);
            } else if (isWithinWeek(millis)) {
                dateString = DateUtils.formatDateTime(c, millis,
                        DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY);
            } else if (isWithinYear(millis)) {
                dateString = DateUtils.formatDateTime(c, millis,
                        DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR
                                | DateUtils.FORMAT_ABBREV_ALL);
            } else {
                dateString = DateUtils.formatDateTime(c, millis,
                        DateUtils.FORMAT_NUMERIC_DATE);
            }
            return dateString;
        }
    
        /**
         * To format the Current time
         * 
         * @param dateFormat
         * @return formated current time value.
         */
        public static String formatCurrentTime(String dateFormat) {
            return formatDate(System.currentTimeMillis(), dateFormat);
        }
    
        /**
         * To format the time in a readable given format.
         * 
         * @param milliSeconds - Time in milliseconds
         * @param dateFormat - Format date
         * @return formated time value.
         */
        public static String formatDate(long milliSeconds, String dateFormat) {
            if (dateFormat == null) {
                dateFormat = "hh:mm:ss.SSS";
            }
            SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    
            /**
             * we are creating the calendar instance and setting the time value.
             */
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(milliSeconds);
    
            return formatter.format(calendar.getTime());
        }
    }