Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active December 26, 2015 12:59
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 micah1701/fa916109e296373a1cda to your computer and use it in GitHub Desktop.
Save micah1701/fa916109e296373a1cda to your computer and use it in GitHub Desktop.
PHP function to convert a timestamp in the past to a human readable, rounded time frame. For example "2 years ago" or "1 minute ago" or even "Just Now" if in past X number of seconds.
<?php
function time_ago($pastTime)
{
$datetime1=new DateTime("now");
$datetime2=date_create($pastTime);
$diff=date_diff($datetime1, $datetime2);
$timemsg='';
if($diff->y > 0){
$timemsg = $diff->y .' year'. ($diff->y > 1?"'s":'');
}
else if($diff->m > 0){
$timemsg = $diff->m . ' month'. ($diff->m > 1?"s":'') .' ago';
}
else if($diff->d > 0){
$timemsg = $diff->d .' day'. ($diff->d > 1?"s":'') .' ago';
}
else if($diff->h > 0){
$timemsg = $diff->h .' hour'.($diff->h > 1 ? "s":'') .' ago';
}
else if($diff->i > 0){
$timemsg = $diff->i .' minute'. ($diff->i > 1?"s":'') .' ago';
}
else if($diff->s > 20){
$timemsg = $diff->s .' second'. ($diff->s > 1?"s":'') .' ago';
}
else if($diff->s >= 0){
$timemsg = 'Just now';
}
return $timemsg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment