Created
August 26, 2011 12:47
-
-
Save joelcox/1173336 to your computer and use it in GitHub Desktop.
Time ago
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($time) | |
{ | |
$time = (is_numeric($time) ? $time : strtotime($time)); | |
$delta = time() - $time; | |
switch (TRUE) | |
{ | |
case ($delta < 0): | |
$str = 'Time is in the future!'; | |
break; | |
case ($delta < 60): | |
$str = 'less than a minute ago'; | |
break; | |
case ($delta < 120): | |
$str = 'a minute ago'; | |
break; | |
case ($delta < 3600): | |
$str = round($delta / 60) . ' minutes ago'; | |
break; | |
case ($delta < 7200): | |
$str = 'a hour ago'; | |
break; | |
case ($delta < 3600 * 24): | |
$str = round($delta / 3600) . ' hours ago'; | |
break; | |
case ($delta < 3600 * 48): | |
$str = 'a day ago'; | |
break; | |
default: | |
$str = round($delta / 86400) . ' days ago'; | |
} | |
return $str; | |
} | |
// 3 seconds ago | |
var_dump(time_ago(time() - 3)); | |
// 1,5 minute ago | |
var_dump(time_ago(time() - 90)); | |
// 3 minute ago | |
var_dump(time_ago(time() - 180)); | |
// 1,5 hour ago | |
var_dump(time_ago(time() - 3600 * 1.5)); | |
// 3 hours ago | |
var_dump(time_ago(time() - 3600 * 3)); | |
// 25 hours ago | |
var_dump(time_ago(time() - 3600 * 25)); | |
// 5 days ago | |
var_dump(time_ago(time() - 3600 * 24 * 5)); | |
// And strings! | |
var_dump(time_ago('Thursday, August 25, 23:00')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment