Created
July 17, 2015 22:26
-
-
Save kurtschlatzer/1a89f26e5ba5a02e3f1a to your computer and use it in GitHub Desktop.
PHP time-ago function
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
function timeAgo($time_ago) { | |
$cur_time = time(); | |
$time_elapsed = $cur_time - $time_ago; | |
$seconds = $time_elapsed ; | |
$minutes = round($time_elapsed / 60 ); | |
$hours = round($time_elapsed / 3600); | |
$days = round($time_elapsed / 86400 ); | |
$weeks = round($time_elapsed / 604800); | |
$months = round($time_elapsed / 2600640 ); | |
$years = round($time_elapsed / 31207680 ); | |
// Seconds | |
if($seconds <= 60){ | |
return "just now"; | |
} | |
//Minutes | |
else if($minutes <=60){ | |
if($minutes==1){ | |
return "one minute ago"; | |
} | |
else{ | |
return "$minutes minutes ago"; | |
} | |
} | |
//Hours | |
else if($hours <=24){ | |
if($hours==1){ | |
return "an hour ago"; | |
}else{ | |
return "$hours hrs ago"; | |
} | |
} | |
//Days | |
else if($days <= 7){ | |
if($days==1){ | |
return "yesterday"; | |
}else{ | |
return "$days days ago"; | |
} | |
} | |
//Weeks | |
else if($weeks <= 4.3){ | |
if($weeks==1){ | |
return "a week ago"; | |
}else{ | |
return "$weeks weeks ago"; | |
} | |
} | |
//Months | |
else if($months <=12){ | |
if($months==1){ | |
return "a month ago"; | |
}else{ | |
return "$months months ago"; | |
} | |
} | |
//Years | |
else{ | |
if($years==1){ | |
return "one year ago"; | |
}else{ | |
return "$years years ago"; | |
} | |
} | |
} | |
echo "<h2>See examples for random timestamps</h2>"; | |
$timestamp = rand(100000000,1000000000); | |
echo "<b>".$timestamp."</b>: " . timeAgo($timestamp) . "<br>"; | |
$timestamp = time()-rand(1000000,10000000); | |
echo "<b>".$timestamp."</b>: " . timeAgo($timestamp) . "<br>"; | |
$timestamp = time()-rand(10000,1000000); | |
echo "<b>".$timestamp."</b>: " . timeAgo($timestamp) . "<br>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment