按月Codeigniter循环日期

时间:2018-02-05 06:11:14

标签: php codeigniter date datetime

我想循环开始日期和结束日期,并按月生成日期。我使用这段代码:

<?php
    $start    = (new DateTime($cust_data->date_sold));
    $end      = (new DateTime($cust_data->due_date));
    $interval = DateInterval::createFromDateString('1 month');
    $period   = new DatePeriod($start, $interval, $end);

    foreach ($period as $dt) {
       echo "<tr>";
       echo "<td>".$dt->format("m-d-Y")."</td>";
       echo "</tr>";
    }

日期示例:

$start = '02-05-2018'
$end = '08-05-2018'

结果:

02-05-2018

03-05-2018

04-05-2018

05-05-2018

06-05-2018

07-05-2018

我希望它是这样的:

03-05-2018

04-05-2018

05-05-2018

06-05-2018

07-05-2018

08-05-2018

但我不知道如何。

2 个答案:

答案 0 :(得分:1)

一种仅使用原生DateTime工具而无需再次解析日期的方法。

$start = (new DateTime($cust_data->date_sold))->modify('+1 day');
$end = (new DateTime($cust_data->due_date))->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
    echo $dt->format("d-m-Y") . '<br>';
}

答案 1 :(得分:0)

希望这会对你有帮助。

    $s1 = date('d-m-Y', strtotime('02-05-2018' . ' + 1 day')); // Added one day to start from 03-05-2018
    $s2 = date('d-m-Y', strtotime('08-05-2018'.' + 1 day')); //Added one day to end with 08-05-2018
    $start = new DateTime($s1);
    $end   = new DateTime($s2);
    $interval = DateInterval::createFromDateString('1 day');
    $period   = new DatePeriod($start, $interval, $end);
    foreach ($period as $dt) {
       echo "<pre>".$dt->format("d-m-Y");
    }  

我已按照d-m-y格式添加了代码。你可以根据需要改变。