Skip to content

Instantly share code, notes, and snippets.

@evanpurkhiser
Created October 21, 2012 08:19
Show Gist options
  • Save evanpurkhiser/3926306 to your computer and use it in GitHub Desktop.
Save evanpurkhiser/3926306 to your computer and use it in GitHub Desktop.
Human readable span date function
Class Date extends Kohana_Date {
/**
* Present the diffidence between two times in a natural format for humans
*
* If the difference is less than a day, then the difference in seconds,
* minutes, or hours will be reported.
*
* $span = Date::human_span(time() - 240); // "4 minutes ago"
* $span = Date::human_span(time() + 1); // "in 1 second"
*
* If the date is more than a day away but less than a week then the name of
* the week will be used
*
* $span = Date::human_span(time() - 172800); // "this past Monday"
* $span = Date::human_span(time() + 172800); // "this coming Friday"
*
* Finally if its more than a week away then a formated date will be
* returned. If the date is more than a year away, then the year will be
* appended to the format
*
* @param int $timestamp "remote" timestamp
* @param int $local_time "local" timestamp, defaults to time()
* @param string $format The format for when a formated date is used
* @return string
*/
public static function human_span($timestamp, $local_time = NULL, $format = 'F jS')
{
$local_time = ($local_time === NULL) ? time() : (int) $local_time;
$offset = abs($timestamp - $local_time);
// Get the how many hours, minutes, and seconds ago it was
$spans = Date::span($timestamp, $local_time, 'hours,minutes,seconds');
$spans = array_filter($spans);
if ($offset < Date::DAY)
{
$name = key($spans);
$time = current($spans);
$date = $time.' '.Inflector::singular($name, $time);
if ($timestamp <= $local_time)
{
// This is in the past
return $date.' ago';
}
// This in the future
return 'in '.$date;
}
// Return the day of the past week
if ($offset < Date::WEEK)
{
$date = date('l', $timestamp);
if ($timestamp <= $local_time)
{
// This is in the past
return 'this past '.$date;
}
// This in the future
return 'this coming '.$date;
}
// Return the formatted date
if ($offset < Date::YEAR)
{
return date($format);
}
// Return the formatted date with the year
return date($format.', Y');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment