Welcome Guest, Not a member yet? Register   Sign In
Date subtraction
#1

[eluser]ilSignorCarlo[/eluser]
Hi,
I need to perform some "simple" operations on dates, for example: getting the distance in days between two dates, or between now and a date in the past.

Code:
$previous_date = '2009-07-03';

// time() actually prints 2009-07-04

echo date('d', (time() - strtotime($previous_date));

This prints 02, but I'm not sure what it is. I mean, if it represents days, it should be 01.
Where am I wrong?

Thanks.
#2

[eluser]jedd[/eluser]
Why not use timespan() ?
#3

[eluser]garymardell[/eluser]
Code:
$previous_date = '2009-07-03';
// time() actually prints 2009-07-04
$diff = time() - strtotime($previous_date);
echo floor(($diff / (60 * 60 * 24)));

Not saying this is the best way to do it, just made your code example work.
#4

[eluser]jedd[/eluser]
In my views I make a call to a function in my helper:
Code:
echo pdb_rough_time_ago  (mysql_to_unix($msgdate)) . " ago";

$msgdate is in mysql format, of course. One day I'll write my helper function to be a bit more adept at recognising and coping with different date formats.

My helper contains:
Code:
/**
* shows pretty rough 'time ago' string
*
* @param string unix date stamp
* @return string
*/
function pdb_rough_time_ago ($date)  {
     /// @TODO cope with non-unix date stamps
     /// @TODO cope with multiple parameters for showing arbitrary diff-between two dates
     /// @TODO get more sophisticated - if it's > 10 hours, don't show minutes .. that kind of thing
    $difference = timespan ($date);

    // If it's only minutes, or hours + minutes, don't mess with it,
    // otherwise just show two most significant components.
    if ( substr_count($difference, ",") > 1)  {
        $date_array = explode (", ", $difference);
        $difference = $date_array[0] .", ". $date_array[1];
        }

    return $difference;
    }

While this diverges slightly from the original question - it's a 'rough time' example after all - it gives an idea of the benefits of using [url="http://ellislab.com/codeigniter/user-guide/helpers/date_helper.html"]CI's date helper[/url] (which is kind of the point isn't it)?
#5

[eluser]ilSignorCarlo[/eluser]
[quote author="jedd" date="1246738247"]Why not use timespan() ?[/quote]

You're right, I just didn't see it Big Grin

Thanks for the other solutions too.




Theme © iAndrew 2016 - Forum software by © MyBB