经历两个日期之间的每一天

时间:2019-06-25 06:04:21

标签: php datetime while-loop

$start_dt = "2019-02-14";
$dt1_obj = new DateTime($start_dt);
$end_dt = "2019-05-05";
$dt2_obj = new DateTime($end_dt);


// get every day from $start_dt date to  $end_dt   
while ( $dt1_obj->add(new DateInterval('P1D'))->format('Y-m-d') <= $end_dt ) {
    $ddd = $dt1_obj;
    echo $ddd->sub(new DateInterval('P1D'))->format('Y-m-d');
    echo "\n";  
}

这是一个无休止的循环。是什么原因?

3 个答案:

答案 0 :(得分:1)

尝试一下,它应该可以工作。

 $start_dt = "2019-02-14"; 
 $end_dt = "2019-05-05"; 
 $period = new DatePeriod(
           new DateTime($start_dt),
           new DateInterval('P1D'),
           new DateTime($end_dt)
 );

要获取日期,您应该进行迭代

 foreach ($period as $key => $value) {
    //$value->format('Y-m-d')       
 }

答案 1 :(得分:1)

您在循环条件中添加了一天,然后在循环的主体中减去了一天(请注意,$ddd只是对相同DateTime对象的另一个引用!)。您可以提前一天开始并在循环中打印日期本身:

$start_dt = "2019-02-13";
$dt1_obj = new DateTime($start_dt);
$end_dt = "2019-05-05";
$dt2_obj = new DateTime($end_dt);

// get every day from $start_dt date to  $end_dt   
while ( $dt1_obj->add(new DateInterval('P1D'))->format('Y-m-d') <= $end_dt ) {
    echo $dt1_obj->format('Y-m-d');
    echo "\n";  
}

答案 2 :(得分:0)

问题是因为您添加了一天,然后减去了一天……请尝试

// get every day from $start_dt date to  $end_dt   
while ( $dt1_obj->add(new DateInterval('P1D'))->format('Y-m-d') <= $end_dt ) {
    $ddd = $dt1_obj;
    echo $ddd->format('Y-m-d');
    echo "\n";  
}