How can I subtract an older date 2010-10-18 07:44:53 from a newer date using PHP?
            Asked
            
        
        
            Active
            
        
            Viewed 581 times
        
    1
            
            
         
    
    
        HELP
        
- 14,237
- 22
- 66
- 100
- 
                    possible duplicate of [How to calculate the date difference between 2 dates using php](http://stackoverflow.com/questions/676824/how-to-calculate-the-date-difference-between-2-dates-using-php) – Gordon Oct 19 '10 at 08:43
3 Answers
0
            
            
        date_diff
http://php.net/manual/en/function.date-diff.php
If you are using DateTime objects the method is diff
 
    
    
        Diego
        
- 16,436
- 26
- 84
- 136
- 
                    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 – doppelgreener Oct 18 '10 at 15:54
- 
                    In the link there is the code to make the function in the case PHP < 5.3 – Diego Oct 18 '10 at 15:55
0
            
            
        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
        
- 22,273
- 19
- 57
- 75
