Android 时间格式化(刚刚、x分钟前、x小时前、昨天、x天前、xx月xx日、xxxx年xx月xx日)

最近公司项目在搞动态相关的,产品昨天给出了时间格式,下午花了一点时间搞了一下,分享给大家。

1 分钟以内:刚刚

1-2分钟:1分钟前

过了1个小时(60分钟以内使用xx分钟前):1小时前

过了1个24:00:昨天

过了2个24:00:2天前

不是本年:xxxx年xx月xx日

public class TimeHelp {

    public static String format(long timeMillis) {
        return format(new Date(timeMillis));
    }

    private static String format(Date date) {
        Calendar calendar = Calendar.getInstance();
        //当前年
        int currYear = calendar.get(Calendar.YEAR);
        //当前日
        int currDay = calendar.get(Calendar.DAY_OF_YEAR);
        //当前时
        int currHour = calendar.get(Calendar.HOUR_OF_DAY);
        //当前分
        int currMinute = calendar.get(Calendar.MINUTE);
        //当前秒
        int currSecond = calendar.get(Calendar.SECOND);

        calendar.setTime(date);
        int msgYear = calendar.get(Calendar.YEAR);
        //说明不是同一年
        if (currYear != msgYear) {
            return new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()).format(date);
        }
        int msgDay = calendar.get(Calendar.DAY_OF_YEAR);
        //超过7天,直接显示xx月xx日
        if (currDay - msgDay > 7) {
            return new SimpleDateFormat("MM月dd日", Locale.getDefault()).format(date);
        }
        //不是当天
        if (currDay - msgDay > 0) {
            if (currDay - msgDay == 1) {
                return "昨天";
            } else {
                return currDay - msgDay + "天前";
            }
        }
        int msgHour = calendar.get(Calendar.HOUR_OF_DAY);
        int msgMinute = calendar.get(Calendar.MINUTE);
        //不是当前小时内
        if (currHour - msgHour > 0) {
            //如果当前分钟小,说明最后一个不满一小时
            if (currMinute < msgMinute) {
                if (currHour - msgHour == 1) {//当前只大一个小时值,说明不够一小时
                    return 60 - msgMinute + currMinute + "分钟前";
                } else {
                    return currHour - msgHour - 1 + "小时前";
                }
            }
            //如果当前分钟数大,够了一个周期
            return currHour - msgHour + "小时前";
        }
        int msgSecond = calendar.get(Calendar.SECOND);
        //不是当前分钟内
        if (currMinute - msgMinute > 0) {
            //如果当前秒数小,说明最后一个不满一分钟
            if (currSecond < msgSecond) {
                if (currMinute - msgMinute == 1) {//当前只大一个分钟值,说明不够一分钟
                    return "刚刚";
                } else {
                    return currMinute - msgMinute - 1 + "分钟前";
                }
            }
            //如果当前秒数大,够了一个周期
            return currMinute - msgMinute + "分钟前";
        }
        //x秒前
        return "刚刚";
    }
}
发布了9 篇原创文章 · 获赞 4 · 访问量 1291

猜你喜欢

转载自blog.csdn.net/d_shaoshuai/article/details/105067716