Hey!
I created an extension to the date_helper to output nicer dates.
The function assumes a timestamp OR a date in the format 2009-02-22 12:00:00.
It will compare the input to the current time and create something like:
“4 minutes ago” or “1 month ago”
The helper uses the language class for different languages so you’ll have to add some keys to it to support the new function (included at bottom of post).
Usage in views:
<p>The post was created <?=relative_time('2009-01-22 12:00:00');?></p>
The my_date_helper.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if( ! function_exists('relative_time'))
{
function relative_time($datetime)
{
$CI =& get_instance();
$CI->lang->load('date');
if(!is_numeric($datetime))
{
$val = explode(" ",$datetime);
$date = explode("-",$val[0]);
$time = explode(":",$val[1]);
$datetime = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
}
$difference = time() - $datetime;
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0)
{
$ending = $CI->lang->line('date_ago');
}
else
{
$difference = -$difference;
$ending = $CI->lang->line('date_to_go');
}
for($j = 0; $difference >= $lengths[$j]; $j++)
{
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1)
{
$period = strtolower($CI->lang->line('date_'.$periods[$j].'s'));
} else {
$period = strtolower($CI->lang->line('date_'.$periods[$j]));
}
return "$difference $period $ending";
}
}
The additions to date_lang.php (in your prefered language ofcourse, place in app/languages/your_language/)
$lang['date_decade'] = "Decade";
$lang['date_decades'] = "Decades";
$lang['date_ago'] = "ago";
$lang['date_to_go'] = "to go";
To me this was quite useful, hope someone else likes it.
I will continue to work on it to output “about 5 minutes ago” and stuff like that.
Cheers!
EDIT: Just remembered that I should include a link to the original function, although rewritten quite alot. http://snipplr.com/view.php?codeview&id=12177
