PHP function, time_since
I’m building a site and was looking for a PHP function to say in words how long ago stuff was posted. I couldn’t find one, so I made one based on a JavaScript function my brother dug up.
So, now there is one for the next preson to find. This is also very easy to change to any language; I use it in Swedish.
function time_since($original) {
// accepts a datestring in any format, or a unix timestamp.
$original = strtotime($original);
$today = time();
$distanceInSeconds = $today - $original;
$distanceInMinutes = round($distanceInSeconds / 60);
if ($distanceInMinutes < = 1) {
if ($distanceInSeconds < 30)
return "less than 20 seconds ago";
if ($distanceInSeconds < 40)
return "half a minute ago";
if ($distanceInSeconds < 60)
return "less than a minute ago";
return "1 minute ago";
}
if ($distanceInMinutes < 45)
return "$distanceInMinutes minutes ago";
if ($distanceInMinutes < 90)
return "about an hour ago";
if ($distanceInMinutes < 1440)
return round($distanceInMinutes / 60)." hours ago";
if ($distanceInMinutes < 2880)
return "1 day ago";
if ($distanceInMinutes < 43200)
return round($distanceInMinutes / 1440)." days ago";
if ($distanceInMinutes < 86400)
return "about a month ago";
if ($distanceInMinutes < 525600)
return round($distanceInMinutes / 43200)." months ago";
if ($distanceInMinutes < 1051200)
return "about a year ago";
return round($distanceInMinutes / 525600)." years ago";
}
Ideas - Johan @ 13:22 |


It was more or less a reimplementation of distance_of_time_in_words() from Rails.
Skickat 3/7 -10 @ 23:56I tend to use PHP’s DateTime class to do these kind of things.
Skickat 11/9 -11 @ 16:12How does that work with translations? The particular site was in Swedish
Skickat 11/9 -11 @ 20:35