Skip to content

Instantly share code, notes, and snippets.

@skynet
Created December 11, 2011 17:07
Show Gist options
  • Save skynet/1461589 to your computer and use it in GitHub Desktop.
Save skynet/1461589 to your computer and use it in GitHub Desktop.
DateInterval
/**
* Interval formatting
* Requires php 5.3
* @param DateTime $start
* @param Bool $and
*/
function format_date_diff($start, $and = false) {
if(!($start instanceof DateTime)) {
$start = new DateTime($start);
}
$end = new DateTime();
if(!($end instanceof DateTime)) {
$end = new DateTime($start);
}
$interval = $end->diff($start);
$format = array();
if($interval->y !== 0) {
$format[] = "%y " . plural($interval->y, "year");
}
if($interval->m !== 0) {
$format[] = "%m " . plural($interval->m, "month");
}
if($interval->d !== 0) {
$format[] = "%d " . plural($interval->d, "day");
}
if($interval->h !== 0) {
$format[] = "%h " . plural($interval->h, "hour");
}
if($interval->i !== 0) {
$format[] = "%i " . plural($interval->i, "minute");
}
if($interval->s !== 0) {
if(!count($format)) {
return "less than a minute";
} else {
$format[] = "%s " . plural($interval->s, "second");
}
}
// We use the two biggest parts
if(count($format) > 1) {
$format = array_shift($format) . ($and ? " and " . array_shift($format) : '');
} else {
$format = array_pop($format);
}
// Prepend 'since ' or whatever you like
return $interval->format($format);
}
function plural($n, $s) { return $n > 1 ? $s . 's' : $s; }; // adds plurals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment