Created
April 6, 2011 18:10
-
-
Save codler/906181 to your computer and use it in GitHub Desktop.
relative_date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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