Sammi89
9/8/2015 - 10:05 AM

Manage the date in PHP

Manage the date in PHP

function time_elapsed_string($datetime, $full = false) {
  $now = new DateTime;
  $ago = new DateTime($datetime);
  $diff = $now->diff($ago);

  $diff->w = floor($diff->d / 7);
  $diff->d -= $diff->w * 7;

  $string = array(
    'y' => t('year'),
    'm' => t('month'),
    'w' => t('week'),
    'd' => t('day'),
    'h' => t('hour'),
    'i' => t('minute'),
    's' => t('second'),
  );
  foreach ($string as $k => &$v) {
    if ($diff->$k) {
      $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
    } else {
      unset($string[$k]);
    }
  }

  if (!$full) $string = array_slice($string, 0, 1);
  return $string ? implode(', ', $string) . ' ' . t('ago') : t('just now');
}