azmicolejr

PHP DateTime Ago

Dec 17th, 2018
609
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.69 KB | None | 0 0
  1. function time_elapsed_string($datetime, $full = false) {
  2.   $now = new DateTime;
  3.   $ago = new DateTime($datetime);
  4.   $diff = $now->diff($ago);
  5.  
  6.   $diff->w = floor($diff->d / 7);
  7.   $diff->d -= $diff->w * 7;
  8.  
  9.   $string = array(
  10.       'y' => 'year',
  11.       'm' => 'month',
  12.       'w' => 'week',
  13.       'd' => 'day',
  14.       'h' => 'hour',
  15.       'i' => 'minute',
  16.       's' => 'second',
  17.   );
  18.   foreach ($string as $k => &$v) {
  19.       if ($diff->$k) {
  20.           $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
  21.       } else {
  22.           unset($string[$k]);
  23.       }
  24.   }
  25.  
  26.   if (!$full) $string = array_slice($string, 0, 1);
  27.   return $string ? implode(', ', $string) . ' ago' : 'just now';
  28. }
Advertisement
Add Comment
Please, Sign In to add comment