Skip to content

Instantly share code, notes, and snippets.

@codler
Created April 6, 2011 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codler/906181 to your computer and use it in GitHub Desktop.
Save codler/906181 to your computer and use it in GitHub Desktop.
relative_date
/**
* Convert to relative date
*
* @param int $timestamp In seconds
* @param array $settings
* @param string $default_format
* @return string
* @version 1.0 (2011-12-12)
*/
function relative_date( $timestamp, array $settings = array(), $default_format = 'Y-m-d' ) {
# default settings
# For available keys, see
# http://www.php.net/manual/en/datetime.formats.relative.php
$default = array(
'5 seconds ago' => 'Just now',
'1 minute ago' => 'Less than :seconds seconds ago',
'1 hour ago' => 'Less than :minutes minutes ago',
'1 day ago' => 'Less than :hours hours ago',
'1 week ago' => 'Less than :days days ago',
'5 seconds' => 'Soon',
'1 minute' => ':seconds seconds left',
'1 hour' => ':minutes minutes left',
'1 day' => ':hours hours left',
'1 week' => ':days days left',
);
# merge settings
$settings += $default;
$offset = $timestamp - time();
$abs_offset = abs($offset);
# convert the key, relative format to seconds
foreach(array_keys($settings) AS $key) {
$newkey = strtotime($key, 0);
$settings[$newkey] = $settings[$key];
unset($settings[$key]);
}
# replace :seconds|:minutes|:hours|:days
foreach($settings AS $time => $value) {
$settings[$time] = preg_replace_callback('/(:seconds|:minutes|:hours|:days)/', function ($matches) use ($abs_offset) {
if ($matches[1] == ':seconds') {
return $abs_offset;
} elseif ($matches[1] == ':minutes') {
return ceil($abs_offset / 60);
} elseif ($matches[1] == ':hours') {
return ceil($abs_offset / 60 / 60);
} elseif ($matches[1] == ':days') {
return ceil($abs_offset / 24 / 60 / 60);
}
return $abs_offset;
}, $value);
}
# find suitable text
$nearest = ($offset > 0) ? PHP_INT_MAX : ~PHP_INT_MAX;
foreach($settings AS $time => $value) {
if ($offset > 0) {
if ($offset < $time && $nearest > $time) {
$nearest = $time;
}
} else {
if ($offset > $time && $nearest < $time) {
$nearest = $time;
}
}
}
return (isset($settings[$nearest])) ? $settings[$nearest] : date($default_format, $timestamp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment