简体   繁体   English

未定义的date_diff()

[英]Undefined date_diff()

I'm trying to use 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');

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. 使用PHP 5.2。

Thanks. 谢谢。

The function date_diff requires a PHP version of 5.3 or greater. 函数date_diff需要5.3或更高版本的PHP版本。

UPDATE UPDATE

An example for PHP 5.2 (taken from the date_diff user comments). 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; } 

Here is a version that doesn't use Date objects, but these are of no use anyways in 5.2. 这是一个不使用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));
}

First convert both dates to mm/dd/yyyy format then do this : 首先将两个日期转换为mm / dd / yyyy格式,然后执行以下操作:

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

//this will yield the resultant difference in days

Converting your DateTime to Unix date type, and subtracting one from another: The format->("U") is where the DateTime is converted. 将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);

Not sure if this is Y2K38 safe but it's one of the simplest date_diff workarounds. 不确定这是否是Y2K38安全,但它是最简单的date_diff解决方法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM