Created
December 27, 2015 02:19
-
-
Save WenLiangTseng/654a58e3676b9ff48b25 to your computer and use it in GitHub Desktop.
PHP顯示多少時間之前
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 | |
// reference: http://stackoverflow.com/questions/18685/how-to-display-12-minutes-ago-etc-in-a-php-webpage | |
function timeAgo($timestamp){ | |
$datetime1=new DateTime("now"); | |
$datetime2=date_create($timestamp); | |
$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":''); | |
} | |
else if($diff->d > 0){ | |
$timemsg = $diff->d .' day'. ($diff->d > 1?"'s":''); | |
} | |
else if($diff->h > 0){ | |
$timemsg = $diff->h .' hour'.($diff->h > 1 ? "'s":''); | |
} | |
else if($diff->i > 0){ | |
$timemsg = $diff->i .' minute'. ($diff->i > 1?"'s":''); | |
} | |
else if($diff->s > 0){ | |
$timemsg = $diff->s .' second'. ($diff->s > 1?"'s":''); | |
} | |
$timemsg = $timemsg.' ago'; | |
return $timemsg; | |
} | |
?> | |
<?php | |
// another solution | |
function time_since($since) { | |
$chunks = array( | |
array(60 * 60 * 24 * 365 , 'year'), | |
array(60 * 60 * 24 * 30 , 'month'), | |
array(60 * 60 * 24 * 7, 'week'), | |
array(60 * 60 * 24 , 'day'), | |
array(60 * 60 , 'hour'), | |
array(60 , 'minute'), | |
array(1 , 'second') | |
); | |
for ($i = 0, $j = count($chunks); $i < $j; $i++) { | |
$seconds = $chunks[$i][0]; | |
$name = $chunks[$i][1]; | |
if (($count = floor($since / $seconds)) != 0) { | |
break; | |
} | |
} | |
$print = ($count == 1) ? '1 '.$name : "$count {$name}s"; | |
return $print; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment