java 實現 發佈了多久的時間描述:幾分鐘前,幾小時前,幾天前,幾個月前,幾年前

測試:

    @Test
    public void time() {
        String time = "2017-10-26 15:33:00";
        Date date = strToDateLong(time);
        System.out.println(timeUtile(date));
    }

工具:

 

     public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
        
    String timeUtile(Date inTime) {
        // 拿到當前時間戳和發佈時的時間戳,然後得出時間戳差
        Date curTime = new Date();
        long timeDiff = curTime.getTime() - inTime.getTime();
        //上面一行代碼可以換成以下(兼容性的解決)

        // 單位換算
        long min = 60 * 1000;
        long hour = min * 60;
        long day = hour * 24;
        long week = day * 7;
        long month = week * 4;
        long year = month * 12;
        DecimalFormat df = new DecimalFormat("#");
        // 計算髮布時間距離當前時間的周、天、時、分
        double exceedyear = Math.floor(timeDiff / year);
        double exceedmonth = Math.floor(timeDiff / month);
        double exceedWeek = Math.floor(timeDiff / week);
        double exceedDay = Math.floor(timeDiff / day);
        double exceedHour = Math.floor(timeDiff / hour);
        double exceedMin = Math.floor(timeDiff / min);


        // 最後判斷時間差到底是屬於哪個區間,然後return

        if (exceedyear < 100 && exceedyear > 0) {
            return df.format(exceedyear) + "年前";
        } else {
            if (exceedmonth < 12 && exceedmonth > 0) {
                return df.format(exceedmonth) + "月前";
            } else {
                if (exceedWeek < 4 && exceedWeek > 0) {
                    return df.format(exceedWeek) + "星期前";
                } else {
                    if (exceedDay < 7 && exceedDay > 0) {
                        return df.format(exceedDay) + "天前";
                    } else {
                        if (exceedHour < 24 && exceedHour > 0) {
                            return df.format(exceedHour) + "小時前";
                        } else {
                            return df.format(exceedMin) + "分鐘前";
                        }
                    }
                }
            }
        }
    }

 

發佈了28 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章