Skip to content

Instantly share code, notes, and snippets.

@jak
Created April 22, 2012 19:57
Show Gist options
  • Save jak/2466500 to your computer and use it in GitHub Desktop.
Save jak/2466500 to your computer and use it in GitHub Desktop.
from_time()
<?php
function pluralise($count, $single, $plural = null) {
if ($count == 1 || $count == -1) {
return $single;
}
if ($plural == null) {
$plural = $single . 's';
}
return $plural;
}
function from_time($time) {
$now = new DateTime('now');
$then = new DateTime($time);
$timespan = $now->diff($then);
$message = array();
if ($timespan->y)
$message[] = $timespan->y.' '.pluralise($timespan->y, 'year');
if ($timespan->m)
$message[] = $timespan->m.' '.pluralise($timespan->m, 'month');
if ($timespan->d)
$message[] = $timespan->d.' '.pluralise($timespan->d, 'day');
if ($timespan->h)
$message[] = $timespan->h.' '.pluralise($timespan->h, 'hour');
if ($timespan->i)
$message[] = $timespan->i.' '.pluralise($timespan->i, 'minute');
if ($timespan->s)
$message[] = $timespan->s.' '.pluralise($timespan->s, 'second');
if (count($message) == 0) {
return 'just now';
}
$output = array_shift($message);
if ($message) {
$output .= ' and '.array_shift($message);
}
$output .= ' ago';
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment