Skip to content

Instantly share code, notes, and snippets.

@UchePhilz
Created April 28, 2019 17:23
Show Gist options
  • Save UchePhilz/226de9d9919f870ec1740ddc768294d7 to your computer and use it in GitHub Desktop.
Save UchePhilz/226de9d9919f870ec1740ddc768294d7 to your computer and use it in GitHub Desktop.
function to get the time past from a date
public static function time_elapsed_string($datetime, $full = false, $msgFuture = "to go", $msgPresent = " just now", $msgPast = " ago") {
if (isset($datetime)) {
$now = new \DateTime;
$date = new \DateTime($datetime);
$diff = $now->diff($date);
$datePosition = " ago";
if ($now < $date) {
$datePosition = $msgFuture;
}
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => '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) . $datePosition : 'just now';
}else {
return "not set";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment