Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined date_diff()

Tags:

php

datediff

I'm trying to use date_diff():

$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');

Its doesn't work for me, gives an error:

Call to undefined function  date_diff()

How can I get it work?

PHP 5.2 is used.

Thanks.

like image 428
James Avatar asked Aug 13 '10 09:08

James


2 Answers

The function date_diff requires a PHP version of 5.3 or greater.

UPDATE

An example for PHP 5.2 (taken from the date_diff user comments).

<?php 
function date_diff($date1, $date2) { 
    $current = $date1; 
    $datetime2 = date_create($date2); 
    $count = 0; 
    while(date_create($current) < $datetime2){ 
        $current = gmdate("Y-m-d", strtotime("+1 day", strtotime($current))); 
        $count++; 
    } 
    return $count; 
} 

echo (date_diff('2010-3-9', '2011-4-10')." days <br \>"); 
?>
like image 147
Peter O'Callaghan Avatar answered Nov 05 '22 00:11

Peter O'Callaghan


Here is a version that doesn't use Date objects, but these are of no use anyways in 5.2.

function date_diff($d1, $d2){
    $d1 = (is_string($d1) ? strtotime($d1) : $d1);
    $d2 = (is_string($d2) ? strtotime($d2) : $d2);  
    $diff_secs = abs($d1 - $d2);
    return floor($diff_secs / (3600 * 24));
}
like image 21
pascal Avatar answered Nov 04 '22 23:11

pascal