date helper : date_when() - get time elapsed/to go |
[eluser]ntheorist[/eluser]
I was looking for a helper function to give me a date span in natural english, ie '3 days ago', '2 months from now' etc, but i decided just to write one and add it to CI's date helper. It's working pretty well for me so I thought i'd share it. It uses the date_helper now() function so its best to add it to the helper file. it takes 1 argment, a unix timestamp, with an optional 2nd option to specify a different 'now' time: Code: $time = now() - 4*24*3600; Here it is: Code: if ( ! function_exists('date_when') ) It's not 100% accurate. As with most date stuff it could be improved to include exact number of seconds in current month, account for leap years etc. But since it returns only the highest span of time, only in very narrow circumstances it would output, for instance 'Last Month' where it should output '2 months ago', etc. cheers, _CC
[eluser]sophistry[/eluser]
nice work. i like the clear, concise programming idiom. this is code by someone with a fair bit of experience! i pored over it looking for holes, but besides the "known deficiencies" listed in the original post i couldn't find anything except for this: Code: $past = ($base > $timestamp) ? TRUE : FALSE; could be tightened to: Code: $past = ($base > $timestamp); cheers. EDIT: found another minor glitch - Code: $suffix = $end = ($past) ? ' ago' : ' from now'; should be: Code: $suffix = ($past) ? ' ago' : ' from now';
[eluser]crmdesignstudio[/eluser]
Thanks for this, it's working great for me! The only issue I ran into was after adding a timestamped item, upon redirecting the user to the same page they added it from. After doing so, the relative time would just show " from now" since there is no case to handle when the timestamp is the same as the current time. Just added... Code: // Set period to say '1 second ago' if you redirect user immediately after adding a timestamped item Cheers!
[eluser]techgnome[/eluser]
crmdesign - you do know there is the timespan() function in the date_helper? It's right in the user's guide. http://ellislab.com/codeigniter/user-gui...elper.html don't know how it handles the empty from now bit. But might want to look at it. -tg
[eluser]crmdesignstudio[/eluser]
Thanks techgnome, I did take a look at the timespan() function but I'm also using this to show how much time until an event in the future as well...which is where this helper came into play |
Welcome Guest, Not a member yet? Register Sign In |