[英]Undefined date_diff()
我正在嘗試使用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()
我怎樣才能讓它發揮作用?
使用PHP 5.2。
謝謝。
函數date_diff需要5.3或更高版本的PHP版本。
UPDATE
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 \>");
?>
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; }
這是一個不使用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));
}
首先將兩個日期轉換為mm / dd / yyyy格式,然后執行以下操作:
$DateDiff = floor( strtotime($datetime2 ) - strtotime( $datetime1 ) ) / 86400 ;
//this will yield the resultant difference in days
將DateTime轉換為Unix日期類型,並從另一個中減去:格式 - >(“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解決方法之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.