convert time stamp to time ago in php?

c
Get the current date, given a timezone in PHP?
Convert a date format in PHP

You should use the DateTime class to get the difference between 2 times, ie;

$time1 = new DateTime('2014-10-06 09:00:59');
$now = new DateTime();
$interval = $time1->diff($now,true);

and then use that difference (which is a DateInterval object, $interval) to find the smallest time difference like this;

if ($interval->y) echo $interval->y . ' years';
elseif ($interval->m) echo $interval->m . ' months';
elseif ($interval->d) echo $interval->d . ' days';
elseif ($interval->h) echo $interval->h . ' hours';
elseif ($interval->i) echo $interval->i . ' minutes';
else echo "less than 1 minute";

which should echo (at the time of writing) 13 hours.

Another solution

Check this function intval()

$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));

if ($seconds_ago >= 31536000) {
    echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
    echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
    echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
    echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
    echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
    echo "Seen less than a minute ago";
}
Get the current date, given a timezone in PHP?
Convert a date format in PHP

Add comment

Tutor Network

Share this

Learn PHP from A to Z