Android 時間格式化(剛剛、x分鐘前、x小時前、昨天、x天前、xx月xx日、xxxx年xx月xx日)

最近公司項目在搞動態相關的,產品昨天給出了時間格式,下午花了一點時間搞了一下,分享給大家。

1 分鐘以內:剛剛

1-2分鐘:1分鐘前

過了1個小時(60分鐘以內使用xx分鐘前):1小時前

過了1個24:00:昨天

過了2個24:00:2天前

過了7個24:00:xx月xx日

不是本年: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 "剛剛";
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章