tags:

views:

42

answers:

3

How can I subtract an older date 2010-10-18 07:44:53 from a newer date using PHP?

A: 

date_diff

http://php.net/manual/en/function.date-diff.php

If you are using DateTime objects the method is diff

Diego
PHP >= 5.3.0 only
Spilarix
is there another way?
huf
For an alternative, there's the answer to this question: http://stackoverflow.com/questions/676824/how-to-calculate-the-date-difference-between-2-dates-using-php
Axidos
In the link there is the code to make the function in the case PHP < 5.3
Diego
A: 

I would advise working with timestamps. subtract one from the other, the difference is seconds, then simple logic to convert it to mins/hours/days ect.

you can use date, strtotime, mktime to get a timestamp

piddl0r
A: 

Answering the question kind of depends on what return value you want. Seconds? Minutes? Here's a simple function you can try to get the value in any form you want:

<?php
define('SUBDATES_SECS', 0);
define('SUBDATES_MINS', 1);
define('SUBDATES_HOURS', 2);
define('SUBDATES_DAYS', 3);
define('SUBDATES_WEEKS', 4);
define('SUBDATES_MONTHS', 5);
define('SUBDATES_YEARS', 6);
function sub_dates($older, $newer, $ret = SUBDATES_SECS) {
    $older = (is_numeric($older)) ? $older : strtotime($older);
    $newer = (is_numeric($newer)) ? $newer : strtotime($newer);

    $result = $newer - $older;
    switch($ret) {
        case SUBDATES_MINS:
            $result /= 60;
            break;
        case SUBDATES_HOURS:
            $result /= 120;
            break;
        case SUBDATES_DAYS:
            $result /= 86400;
            break;
        case SUBDATES_WEEKS:
            $result /= 604800 ;
            break;
        case SUBDATES_MONTHS:
            $result /= 2629743;
            break;
        case SUBDATES_YEARS:
            $result /= 31556926;
            break;
    }

    return $result;
}

Using it:

<?php
$older = time();
sleep(3);
$newer = time();
echo sub_dates($older, $newer);
// Returns 3

echo sub_dates($older, $newer, SUBDATES_MINS);
// Returns 0.05

echo sub_dates('2010-04-19 01:01:00', '2010-04-19 01:02:00', SUBDATES_MINS);
// Returns 1

It's pretty untested though!

mellowsoon