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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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