經常在朋友圈,QQ空間、微博上看到動態的發布時間、評論時間,都顯示,昨天,前天,幾天前,比起直接顯示幾月幾日幾分幾秒要優雅的多。
於是自己的項目也想采用這種優雅直觀的方式,網上找了各種計算相差幾天的的例子,都是直接將時間戳相見除以86400,比如現在是17:08,動態更新的時間為前天22:00,這種方式計算的相差天數為1,而不是兩天前。
實際情況應該是,昨天任何時間都算一天前,前天任意時間都算2天前,所以自己琢磨了一番,去動態更新時間與今天23:59:59相差的時間秒數與86400(24 x 3600)相除后,向下取整,這樣就得到了相差的天數,比如昨天00:00~昨天23:59:59的任何時間與今天的23:59:59,都相差 86400~(86400 x 2) 天,也就是2天。
/** * 獲取已經過了多久 * PHP時間轉換 * 剛剛、幾分鍾前、幾小時前 * 今天昨天前天幾天前 * @param string $targetTime 時間戳 * @return string */ function get_last_time($targetTime) { // 今天最大時間 $todayLast = strtotime(date('Y-m-d 23:59:59')); $agoTimeTrue = time() - $targetTime; $agoTime = $todayLast - $targetTime; $agoDay = floor($agoTime / 86400); if ($agoTimeTrue < 60) { $result = '剛剛'; } elseif ($agoTimeTrue < 3600) { $result = (ceil($agoTimeTrue / 60)) . '分鍾前'; } elseif ($agoTimeTrue < 3600 * 12) { $result = (ceil($agoTimeTrue / 3600)) . '小時前'; } elseif ($agoDay == 0) { $result = '今天 ' . date('H:i', $targetTime); } elseif ($agoDay == 1) { $result = '昨天 ' . date('H:i', $targetTime); } elseif ($agoDay == 2) { $result = '前天 ' . date('H:i', $targetTime); } elseif ($agoDay > 2 && $agoDay < 16) { $result = $agoDay . '天前 ' . date('H:i', $targetTime); } else { $format = date('Y') != date('Y', $targetTime) ? "Y-m-d H:i" : "m-d H:i"; $result = date($format, $targetTime); } return $result; }
private static String converToTimeString(Date time) { Date todayEndTime = DateUtils.getTodayEndTime(); long betweenSecondes = DateUtils.betweenSecondes(todayEndTime, time); int agoDay = new Double(Math.floorDiv(betweenSecondes, 86400)).intValue(); StringBuilder buffer = new StringBuilder(12); if (agoDay == 0) { buffer.append("今天 "); } else if (agoDay == 1) { buffer.append("昨天 "); } else if (agoDay == 2) { buffer.append("前天 "); } else { buffer.append(agoDay).append("天前 "); } buffer.append(DateUtils.convertDateToString(time, DateUtils.HH_MM_SS)); return buffer.toString(); }