I am trying to create a function that compares a date with the current time, and returns a nicely formatted string.
I have written some code in haste and it works, but I am trying to find a more efficient way of doing it. Here is my code:
function _formatDate($dateStr)
{
$timestr = "";
$t= time() - strtotime($dateStr);
if($t < 60) {
$timestr = "{$t} seconds ago";
}
elseif ($t <120) {
$timestr = "about a minute ago";
}
elseif ($t < 3600) {
$minute = floor($t/60);
$timestr = "{$minute} minutes ago";
}
elseif ($t < 7200) {
$timestr = " about an hour ago";
}
elseif ($t < 86400) {
$hour = floor($t/3600);
$timestr = "{$hour} hours ago";
}
elseif ($t < 172800) {
$timestr = "a day ago";
}
elseif ($t < 2592000) {
$day = floor($t/86400);
$timestr = "{$day} days ago";
}
elseif ($t < 5184000){
$timestr = "about a month ago";
}
else {
$month = floor($t/2592000);
$timestr = "{$month} months ago";
}
return $timestr;
}
See Question&Answers more detail:os