Skip to content

Instantly share code, notes, and snippets.

@u01jmg3
Created February 20, 2017 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u01jmg3/b9adf5037065f8a6be71cd916bb24969 to your computer and use it in GitHub Desktop.
Save u01jmg3/b9adf5037065f8a6be71cd916bb24969 to your computer and use it in GitHub Desktop.
From a timestamp return the relative time
<?php
function getRelativeTime($timestamp) {
$difference = strtotime(date('Y-m-d H:i:s')) - strtotime($timestamp);
$periods = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
$lengths = [60, 60, 24, 7, 4.35, 12, 10];
// This was in the past
if ($difference >= 0) {
$ending = 'ago';
// This was in the future
} else if ($difference < 0) {
$difference = -$difference;
$ending = 'to go';
}
$j = 0;
while ($difference >= $lengths[$j] && $j < count($lengths)) {
$difference /= $lengths[$j];
$j++;
}
$difference = round($difference);
if ($difference != 1) {
$periods[$j] .= 's';
}
$text = "$difference $periods[$j] $ending";
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment