美文网首页
Android-记录一个时间格式的方法

Android-记录一个时间格式的方法

作者: 阿博聊编程 | 来源:发表于2022-10-27 22:43 被阅读0次
图片来源网络,入侵必删

最近在项目开发当中,我们需要对后端接口返回的时间戳进行转换展示,展示格式大概是下面这样:

  • 几秒前
  • 几分钟
  • 几小时
  • 今天
  • 昨天
  • ....
public 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 "刚刚";
    }

我直接封装成方法,可以直接调用处理。这样就可以在其他项目类似的需求当中改进或者直接使用。

相关文章

网友评论

      本文标题:Android-记录一个时间格式的方法

      本文链接:https://www.haomeiwen.com/subject/xdqxtdtx.html