Class' DateInterval'未找到

时间:2014-05-07 09:31:17

标签: php date dateinterval

我想获取除上次日期之外的两个日期之间的日期,以下代码我将用于查找日期。但它引发了一个错误说:

  

未找到类'DateInterval'

代码:

$start = new DateTime('2014-08-06');
$end = new DateTime('2014-09-06');
$oneday = new DateInterval("P1D");

$days = array();
$data = "7.5";

foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
    $day_num = $day->format("N");

    if($day_num < 6) { 
        $days[$day->format("Y-m-d")] = $data;
    } 
} 

print_r($days);

3 个答案:

答案 0 :(得分:0)

PHP的DateInterval class是在PHP 5.3.0版本中引入的,所以如果你使用较低版本的PHP,你会得到错误,说它不知道那个类。

如果您确实使用的PHP版本低于5.3.0,我强烈建议您升级PHP版本。

答案 1 :(得分:0)

看起来你的php版本没有DateInterval类。以下是使用strtotime()的替代方法:

$start = '2014-08-06';
$end = '2014-09-06';

$num_days = floor((strtotime($end)-strtotime($start))/(60*60*24));
$data = '7.5';

$days = array();

for ($i=0; $i<$num_days; $i++) 
    if (date('N', strtotime($start . "+ $i days")) < 6)
        $days[date('Y-m-d', strtotime($start . "+ $i days"))] = $data;

print_r($days);

结果:

Array
(
    [2014-08-06] => 7.5
    [2014-08-07] => 7.5
    [2014-08-08] => 7.5
    [2014-08-11] => 7.5
    [2014-08-12] => 7.5
    [2014-08-13] => 7.5
    [2014-08-14] => 7.5
    [2014-08-15] => 7.5
    [2014-08-18] => 7.5
    [2014-08-19] => 7.5
    [2014-08-20] => 7.5
    [2014-08-21] => 7.5
    [2014-08-22] => 7.5
    [2014-08-25] => 7.5
    [2014-08-26] => 7.5
    [2014-08-27] => 7.5
    [2014-08-28] => 7.5
    [2014-08-29] => 7.5
    [2014-09-01] => 7.5
    [2014-09-02] => 7.5
    [2014-09-03] => 7.5
    [2014-09-04] => 7.5
    [2014-09-05] => 7.5
)

答案 2 :(得分:0)

$begin = new DateTime('2014-08-06');
$end = new DateTime('2014-09-06');
$end = $end->modify( '+1 day' ); 
$days = array();
$data = "7.5";
    while($begin < $end) {
        $day_num = $begin->format("N"); 
            if($day_num < 6) { 
                   $days[$begin->format("Y-m-d")] = $data;
            } 
            $begin->modify('+1 day');
    }
print_r($days);

//输出: -

Array
(
    [2014-08-06] => 7.5
    [2014-08-07] => 7.5
    [2014-08-08] => 7.5
    [2014-08-11] => 7.5
    [2014-08-12] => 7.5
    [2014-08-13] => 7.5
    [2014-08-14] => 7.5
    [2014-08-15] => 7.5
    [2014-08-18] => 7.5
    [2014-08-19] => 7.5
    [2014-08-20] => 7.5
    [2014-08-21] => 7.5
    [2014-08-22] => 7.5
    [2014-08-25] => 7.5
    [2014-08-26] => 7.5
    [2014-08-27] => 7.5
    [2014-08-28] => 7.5
    [2014-08-29] => 7.5
    [2014-09-01] => 7.5
    [2014-09-02] => 7.5
    [2014-09-03] => 7.5
    [2014-09-04] => 7.5
    [2014-09-05] => 7.5
)