Skip to content

Instantly share code, notes, and snippets.

@chill117
Last active December 19, 2015 14:48
Show Gist options
  • Save chill117/5971425 to your computer and use it in GitHub Desktop.
Save chill117/5971425 to your computer and use it in GitHub Desktop.
Quick, handy time format functions. Useful for GUIs or whenever a human-friendly time format is preferred over a timestamp or machine-readable date-time format.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|----------------------------------------------------------------
| Description
|----------------------------------------------------------------
Quick, handy time format functions. Useful for GUIs or whenever
a human-friendly time format is preferred over a timestamp or
machine-readable date-time format.
|----------------------------------------------------------------
| Dependencies
|----------------------------------------------------------------
CodeIgniter
|----------------------------------------------------------------
| Example Usage
|----------------------------------------------------------------
<?php
$ten_minutes_from_now = date('Y-m-d H:i:s', time() + 600);
echo relative_time_format($ten_minutes_from_now);
?>
Should print the following:
10 minutes from now
<?php
$some_datetime = '2013-07-10 19:16:19';
echo human_time_format($some_datetime);
?>
Should print the following:
July 10, 2013 at 7:17 pm
*/
function relative_time_format($datetime)
{
$timestamp = strtotime($datetime);
if (!$timestamp)
return '';
$diff = time() - $timestamp;
$ending = $diff >= 0 ? 'ago' : 'from now';
return time_diff_to_string($diff) . ' ' . $ending;
}
function time_diff_to_string($diff)
{
$periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade');
$lengths = array(60, 60, 24, 7, 4.35, 12, 10);
$diff = abs($diff);
for ($j = 0; $diff >= $lengths[$j]; $j++)
$diff /= $lengths[$j];
$diff = round($diff);
if ($diff != 1)
$periods[$j] .= 's';
return $diff . ' ' . $periods[$j];
}
function human_time_format($datetime)
{
return date('F j, Y', strtotime($datetime)) . ' at ' . date('g:i a', strtotime($datetime));
}
/* End of file time_format_helper.php */
/* Location: ./application/helpers/time_format_helper.php */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment