7

私は使用しようとしています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');

それは私には機能しません、エラーが発生します:

Call to undefined function  date_diff()

どうすればそれを機能させることができますか?

PHP5.2が使用されます。

ありがとう。

4

5 に答える 5

12

関数date_diffには、5.3以降のPHPバージョンが必要です。

アップデート

PHP 5.2の例(date_diffユーザーコメントから取得)。

<?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 \>"); 
?>
于 2010-08-13T09:42:53.447 に答える
1

これはDateオブジェクトを使用しないバージョンですが、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));
}
于 2011-11-19T21:54:49.443 に答える
1
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; } 
于 2012-10-14T16:31:48.540 に答える
1

最初に両方の日付を mm/dd/yyyy 形式に変換してから、次のようにします。

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

//this will yield the resultant difference in days
于 2013-09-21T06:30:46.950 に答える
0

DateTime を Unix 日付型に変換し、別の日付から減算する: format->("U") は、DateTime が変換される場所です。

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

これが Y2K38 に安全かどうかはわかりませんが、date_diff の最も簡単な回避策の 1 つです。

于 2017-01-12T05:57:09.877 に答える