EllisLab text mark
Advanced Search
     
Nicer dates (extending date_helper.php)
Posted: 22 February 2009 10:22 AM
Avatar
Joined: 2008-03-28
430 posts

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

 Signature 

———————————————————————————————————————————-
Imac 27” Core i7 / 12GB RAM
Macbook Pro 15” C2D 2.53Ghz / 4GB RAM / NVIDIA GeForce 9400M + 9600M GT 512MB
iPhone 4 16Gb Black

http://www.rockkarusellen.se

 
Posted: 23 February 2009 11:59 AM   [ # 1 ]   [ Rating: 0 ]
Joined: 2008-03-27
153 posts

This looks like it could be really useful!  I’d love to see this be able to adjust for timezone and daylight savings time as well.  Should be pretty easy to add both as parameters to the function and then take them into account when creating the date at the start.  smile

 
Posted: 23 February 2009 12:19 PM   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2007-06-11
2987 posts
AgentPhoenix - 23 February 2009 04:59 PM

This looks like it could be really useful!  I’d love to see this be able to adjust for timezone and daylight savings time as well.  Should be pretty easy to add both as parameters to the function and then take them into account when creating the date at the start.  smile

Good stuff. I wrote a similar function a while ago but was not anywhere near as clean as this one.

Should this not be using now() instead of time()?

 Signature 

————————
Blog | Twitter | GitHub | BitBucket
————————-
PyroCMS - open source modular CMS built with CodeIgniter
PancakeApp - Simple, hosted invoicing/w project management

 
Posted: 23 February 2009 12:20 PM   [ # 3 ]   [ Rating: 0 ]
Joined: 2006-07-14
4237 posts
Phil Sturgeon - 23 February 2009 05:19 PM

Should this not be using now() instead of time()?

now is not a php function AFAIK

 
Posted: 23 February 2009 12:43 PM   [ # 4 ]   [ Rating: 0 ]
Avatar
Joined: 2008-03-28
430 posts
xwero - 23 February 2009 05:20 PM
Phil Sturgeon - 23 February 2009 05:19 PM

Should this not be using now() instead of time()?

now is not a php function AFAIK

Actually now() is a function in the date-helper (which my function extends) so probably it would be the best.. smile

 Signature 

———————————————————————————————————————————-
Imac 27” Core i7 / 12GB RAM
Macbook Pro 15” C2D 2.53Ghz / 4GB RAM / NVIDIA GeForce 9400M + 9600M GT 512MB
iPhone 4 16Gb Black

http://www.rockkarusellen.se

 
Posted: 23 February 2009 01:04 PM   [ # 5 ]   [ Rating: 0 ]
Joined: 2006-07-14
4237 posts

Have you seen the now function code? It is a bit messy. This is the cleaned up version

function now()

   
return (strtolower(config_item('time_reference')) == 'gmt') ? gmmktime() : time() ;
 
Posted: 23 February 2009 03:16 PM   [ # 6 ]   [ Rating: 0 ]
Avatar
Joined: 2008-03-28
430 posts
xwero - 23 February 2009 06:04 PM

Have you seen the now function code? It is a bit messy. This is the cleaned up version

function now()

   
return (strtolower(config_item('time_reference')) == 'gmt') ? gmmktime() : time() ;

Nope, did not check it out. And still havent!
Your code look great though… smile

 Signature 

———————————————————————————————————————————-
Imac 27” Core i7 / 12GB RAM
Macbook Pro 15” C2D 2.53Ghz / 4GB RAM / NVIDIA GeForce 9400M + 9600M GT 512MB
iPhone 4 16Gb Black

http://www.rockkarusellen.se

 
Posted: 23 February 2009 03:34 PM   [ # 7 ]   [ Rating: 0 ]
Joined: 2007-07-15
69 posts
xwero - 23 February 2009 06:04 PM

Have you seen the now function code? It is a bit messy. This is the cleaned up version

function now()

   
return (strtolower(config_item('time_reference')) == 'gmt') ? gmmktime() : time() ;

What does the “?” and then the subsequent “:” do in that code? I’ve seen that syntax style used before but never known what it means / does. Would someone mind explaining to an idiot like me what that means / is called and where i can read more about it?

Cheers! (sorry to thread hijack!)

 
Posted: 23 February 2009 03:37 PM   [ # 8 ]   [ Rating: 0 ]
Avatar
Joined: 2008-05-17
1073 posts

It’s called ternary operator and it is a shorthand for an if/else statement.
Have a look at the php documentation: http://php.net/language.operators.comparison

 
Posted: 23 February 2009 03:59 PM   [ # 9 ]   [ Rating: 0 ]
Joined: 2007-07-15
69 posts

Excellent, cheers! I was struggling to work out how to do a google search for that syntax to try and find out what it is!!

 
Posted: 23 February 2009 05:01 PM   [ # 10 ]   [ Rating: 0 ]
Avatar
Joined: 2009-01-21
109 posts

Searching for weird characters in Google is awful, especially in the context of programming.  It’s pretty ruthless about ignoring characters. Every once in awhile Google Code Search can help… http://www.google.com/codesearch

 Signature 

Do you use CSS or JavaScript? Carabiner makes your life easier.  I promise.

CI-Disqus makes playing with the Disqus API a snap.

 
Posted: 26 January 2010 11:55 AM   [ # 11 ]   [ Rating: 0 ]
Avatar
Joined: 2008-05-17
74 posts

Great contribution Johan. Thanks!

I’ve modified the last sentence from:

return "$difference $period $ending"

to:

return sprintf($CI->lang->line('timespan_format'), $difference$period$ending); 

and added this to date_lang.php (for spanish):

$lang['timespan_format''%3$s %1$s %2$s'

This gives you the ability to support in the same application different languages that require different word order.

With the original code, the output in spanish would be “5 minutos Hace” (“5 minutes ago” in english), and that doesn’t make sense in spanish, you could rewrite it as “5 minutos atrás” but it sounds a bit awkward, it is more natural to say “Hace 5 minutos”. So giving the user the ability to override the word order per language is, in my opinion, the best option.

 Signature 

janogarcia.es, @janogarcia
margenn - web studio, San Sebastian (Spain) $CI = new $class();

 
Posted: 18 June 2010 11:46 PM   [ # 12 ]   [ Rating: 0 ]
Avatar
Joined: 2009-02-28
16 posts

Thanks for this, Johan. And very thanks for u janogarcia, i used your extension.

Here a few notes:

- If u uses the lang library, you’ll has the trouble of the lang setting, you’ll need to change the setup lang in the helper (otherwise you’ll get the default lang). It’s very simple, example:

function relative_time($datetime)
    
{
        $CI 
=& get_instance();

        
// seteo el lenguaje de la interfaz:
        
$current_lang $CI->languages_manager->getUserLangTiny();
        
$CI->lang->load('date'$current_lang );

        if(!
is_numeric($datetime))
        ... 

- I don’t found here the languages files for all, so i copy&paste;my language files:

English:

<?

$lang[
'timespan_format''%1$s %2$s %3$s';

$lang['date_ago']    "ago";
$lang['date_to_go']    "to go"

$lang['date_second']    "sencond"
$lang['date_seconds']    "seconds"
$lang['date_minute']    "minute"
$lang['date_minutes']    "minutes"
$lang['date_hour']    "hour"
$lang['date_hours']    "hours"
$lang['date_day']    "day"
$lang['date_days']    "days"
$lang['date_week']    "week"
$lang['date_weeks']    "weeks"
$lang['date_month']    "month"
$lang['date_months']    "months"
$lang['date_year']    "year"
$lang['date_years']    "years"
$lang['date_decade'"Decade";
$lang['date_decades'"Decades";

?> 

Spanish:

<?

$lang[
'timespan_format''%3$s %1$s %2$s';

$lang['date_ago']    "Hace";
$lang['date_to_go']    "Faltan";

$lang['date_second']    "segundo";
$lang['date_seconds']    "segundos";
$lang['date_minute']    "minuto";
$lang['date_minutes']    "minutos";
$lang['date_hour']    "hora";
$lang['date_hours']    "horas";
$lang['date_day']    "dia";
$lang['date_days']    "dias";
$lang['date_week']    "semana";
$lang['date_weeks']    "semanas";
$lang['date_month']    "mes";
$lang['date_months']    "meses";
$lang['date_year']    "año";
$lang['date_years']    "años";
$lang['date_decade'"decada";
$lang['date_decades'"decadas";

?> 

thanks guys, this is very usefull wink

 
Posted: 31 March 2011 08:35 PM   [ # 13 ]   [ Rating: 0 ]
Joined: 2011-03-27
1 posts

I Suggest this piece of code for this topic, of course i’m based on previous contributions of this thread, and the multilanguage identifier library.
You can get language files in codeigniter.com/wiki/Language_Translation/
You can get the “old library” of multilanguage in codeigniter.com/wiki/URI_Language_Identifier/

I hope someone wins time with this.

if (!function_exists('relative_time')) {

    
function relative_time($date{
        $diff 
time() - strtotime($date);
        if (
$diff 0{
            
if ($diff 60)
                return 
$diff " " strtolower(($diff>t('date_seconds'):t('date_second'))) . ' ' t('ago');
            
$diff round($diff 60);
            if (
$diff 60)
                return 
$diff " " strtolower(($diff>t('date_minutes'):t('date_minute'))) . ' ' t('ago');
            
$diff round($diff 60);
            if (
$diff 24)
                return 
$diff " " strtolower(($diff>t('date_hours'):t('date_hour'))) . ' ' t('ago');
            
$diff round($diff 24);
            if (
$diff 7)
                return 
$diff " " strtolower(($diff>t('date_days'):t('date_day'))) . ' ' t('ago');
            
$diff round($diff 7);
            if (
$diff 4)
                return 
$diff " " strtolower(($diff>t('date_weeks'):t('date_week'))) . ' ' t('ago');
            return 
"on " date("F j, Y"strtotime($date));
        
}
    }


And the use of t(‘ago’), you will need to define that language item on your language files, example:
english file

$lang['ago']='ago'

and spanish file

$lang['ago']='atrás'

Cheers

 
Posted: 31 March 2011 08:42 PM   [ # 14 ]   [ Rating: 0 ]
Avatar
Joined: 2011-01-30
454 posts

Didn’t even know this item existed. Thanks for the revival. smile

 Signature 

This is the wonderful logo InsiteFX did for me. I had to scale it for this site. But his work is worth showing off.

 
Posted: 28 September 2011 05:40 AM   [ # 15 ]   [ Rating: 0 ]
Avatar
Joined: 2011-07-13
15 posts

Thanks a lot. Worked great for me.

 Signature 

I love CI !

Send E-mails with Gmail Account:
https://github.com/sineld/CI-Gmail