将两个时间戳的差(秒)转化成字符串
比如“x分钟前”、“x小时前”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| <?php
function time2Readability($time, $contrastTime = 0) { if ($contrastTime <= 0) { $contrastTime = time(); }
if ($time <= 0) { return '未知'; }
if (date('Y', $time) != date('Y', $contrastTime)) { return date('Y-m-d H:i:s', $time); }
$dateTime1 = new \DateTime(); $dateTime1->setTimestamp($time); $dateTime1->setTime(0, 0, 0); $time1 = $dateTime1->getTimestamp();
$todayObj = new \DateTime(); $todayObj->setTimestamp($contrastTime); $todayObj->setTime(0, 0, 0); $today = $todayObj->getTimestamp();
$elapseTime = $contrastTime - $time;
if ($time1 == $today) { if ($elapseTime <= 5 * 60) { return '刚刚'; } else if ($elapseTime <= 60 * 60) { return floor($elapseTime / 60) . ' 分钟前'; } else { return floor($elapseTime / (60 * 60)) . ' 小时前'; } }
$dateTime3 = new \DateTime(); $dateTime3->setTimestamp($contrastTime); $dateTime3->modify('-1 day'); $dateTime3->setTime(0, 0, 0); $yesterday = $dateTime3->getTimestamp();
if ($time1 == $yesterday) { if (($contrastTime - 6 * 60 * 60) < $today) { $hourBefore = floor($elapseTime / (60 * 60)); if ($hourBefore <= 9) { return $hourBefore . ' 小时前'; } else { return '昨天:' . date('H:i', $time); } } else { return '昨天:' . date('H:i', $time); } }
return date('m-d H:i:s', $time); } ?>
|
1 2 3 4 5 6 7 8
| $today = new DateTime(); $today->setTime(23, 0, 0);
$t = new DateTime(); $t->modify('-1 year -1 day'); $t->setTime(1, 0, 0);
echo time2Readability($t->getTimestamp(), $today->getTimestamp());
|
参考:https://blog.csdn.net/technofiend/article/details/78627161