getRelativeDateTimeString与星期几?

时间:2017-06-13 08:50:49

标签: android android-dateutils relative-time-span

是否有任何选项可以在星期几获取getRelativeDateTimeString。意味着如果日期在7天内显示为星期一,早上7:14而不是4天前,早上7:14

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

1 个答案:

答案 0 :(得分:2)

嗨,你可以这样使用,

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());
    }
}