From a timestamp return the relative time such as '4 weeks ago'
<?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;
}
Written by Jonathan Goode
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#