Johan Ronström
BLOGG
Jul
2

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 |

3 kommentarer

  1. Erik Ronström skriver:

    It was more or less a reimplementation of distance_of_time_in_words() from Rails.

  2. Svante Kvarnström skriver:

    I tend to use PHP’s DateTime class to do these kind of things.

  3. Johan skriver:

    How does that work with translations? The particular site was in Swedish

Skriv en kommentar

Alla kommentarer godkänns innan de publiceras.

XHTML: Tillåtna tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>