Undefined date_diff()

若如初见. 提交于 2020-02-01 03:35:46

问题


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.


回答1:


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 \>"); 
?>



回答2:


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));
}



回答3:


First convert both dates to mm/dd/yyyy format then do this :

 $DateDiff = floor( strtotime($datetime2 ) - strtotime( $datetime1 ) ) / 86400 ;

//this will yield the resultant difference in days



回答4:


function date_diff($date1, $date2) { 
$count = 0; 
//Ex 2012-10-01 and 2012-10-20
if(strtotime($date1) < strtotime($date2))
{                       
  $current = $date1;                
  while(strtotime($current) < strtotime($date2)){ 
      $current = date("Y-m-d",strtotime("+1 day", strtotime($current))); 
      $count++; 
  } 
}                 
//Ex 2012-10-20 and 2012-10-01
else if(strtotime($date2) < strtotime($date1))
{           
  $current = $date2;                
  while(strtotime($current) < strtotime($date1)){ 
      $current = date("Y-m-d",strtotime("+1 day", strtotime($current))); 
      $count++;  
  }
  $current = $current * -1;
}
return $count; } 



回答5:


Converting your DateTime to Unix date type, and subtracting one from another: The format->("U") is where the DateTime is converted.

$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$intervalInDays = ($datetime2->format("U") - $datetime1->format("U"))/(3600 * 24);

Not sure if this is Y2K38 safe but it's one of the simplest date_diff workarounds.



来源:https://stackoverflow.com/questions/3475646/undefined-date-diff

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!