2010-08-13 34 views
7

Tôi đang cố gắng sử dụng date_diff():date_diff Không xác định()

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

nó không làm việc cho tôi, đưa ra một lỗi:

Call to undefined function date_diff() 

Làm thế nào tôi có thể lấy nó làm việc?

PHP 5.2 được sử dụng.

Cảm ơn.

Trả lời

12

Hàm date_diff yêu cầu phiên bản PHP 5.3 trở lên.

CẬP NHẬT

Một ví dụ cho PHP 5.2 (lấy từ những ý kiến ​​người dùng 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 \>"); 
?> 
+0

Bất kỳ cách nào để sử dụng nó trên PHP 5.2? – James

+0

Đã thêm một biến thể. –

+7

giải pháp này là rất kém hiệu quả – James

1

Đây là phiên bản không sử dụng đối tượng Ngày, nhưng không sử dụng anyways trong 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

Tôi sẽ không khuyên bạn sử dụng phương pháp này vì nó không xem xét các thay đổi thời gian tiết kiệm ánh sáng ban ngày: 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

Vui lòng giải thích câu trả lời của bạn. – hims056

0

Đầu chuyển đổi cả ngày để định dạng/dd/yyyy mm sau đó làm điều này:

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

//this will yield the resultant difference in days 
0

Chuyển đổi DateTime của bạn để Unix kiểu ngày, và trừ một từ khác: Các format- > ("U") là nơi mà DateTime được chuyển đổi.

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

Không chắc chắn đây có phải là Y2K38 an toàn hay không nhưng đây là một trong những cách giải quyết date_diff đơn giản nhất.

Các vấn đề liên quan