2010-08-13 5 views
7

나는 date_diff()를 사용하려고 해요 :정의되지 않은 date_diff()

Call to undefined function 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'); 

그것의 나를 위해 작동하지 않는 오류를 준다?

PHP 5.2가 사용됩니다.

감사합니다.

답변

12

date_diff 함수에는 5.3 이상의 PHP 버전이 필요합니다.

PHP 5.2 일례합니다 (date_diff 사용자 코멘트 찍은) UPDATE.

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

PHP 5.2에서 사용할 수있는 방법은 없나요? – James

+0

변형을 추가했습니다. –

+7

이 솔루션은 매우 비효율적입니다 – James

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

일광 절약 시간제 변경을 고려하지 않기 때문에이 방법을 사용하지 않는 것이 좋습니다. ini_set ('date.timezone', 'America/Los_Angeles') ; echo _date_diff ('2011-03-13', '2011-03-14'); >> 0 –

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; } 
+0

답을 설명해주십시오. – hims056

0

먼저 mm/DD/YYYY 형식으로 두 날짜를 변환하는 것은 다음을 수행하십시오

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

//this will yield the resultant difference in days 
0

는 유닉스 날짜 형식으로 날짜 시간을 변환하고, 다른 하나 빼서 : 포맷팅 및을 > ("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 해결 방법 중 하나입니다.