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
|
public static function friendlyDate($datetime, $size = 1, $absolute = false) { if (is_string($datetime)) { $datetime = new DateTime($datetime); }
if (! ($datetime instanceof DateTime)) { throw new \InvalidArgumentException('invalid "DateTime" object'); }
$now = new DateTime(); if ($absolute && $datetime <= $now) { return ''; }
$interval = $now->diff($datetime);
$intervalData = [ $interval->y, $interval->m, $interval->d, $interval->h, $interval->i, $interval->s, ]; $intervalFormat = ['年', '个月', '天', '小时', '分钟', '秒'];
foreach ($intervalData as $key => $value) { if ($value) { $intervalData[$key] = $value . $intervalFormat[$key]; } else { unset($intervalData[$key]); unset($intervalFormat[$key]); } }
return implode('', array_slice($intervalData, 0, $size)); }
|