如何显示特定月份的所有日期

时间:2016-09-04 07:57:51

标签: php date

使用的代码

$date_from1 = new DateTime('1-9-2016');
$date_from=$date_from1->format('Y-m-d');
$date_to1 = new DateTime('30-9-2016');
$date_to=$date_to1->format('Y-m-d');
$diff1=$date_from1->diff($date_to1);
$diff2= $diff1->format('%R %a days');
preg_match_all('!\d+!', $diff2, $matches); //use that to get only number from diff2
for($i=0; $i <= $matches[0][0]; $i++) //$matches return diff2 only number of days
{
    $this_date=$date_from1->add(new DateInterval('P1D'));
    echo $this_date->format('Y-m-d') . "<br/>";
}

我的输出

  

2016-09-02 2016-09-03 2016-09-04 2016-09-05 2016-09-06 2016-09-07   2016-09-08 2016-09-09 2016-09-10 2016-09-11 2016-09-12 2016-09-13   2016-09-14 2016-09-15 2016-09-16 2016-09-17 2016-09-18 2016-09-19   2016-09-20 2016-09-21 2016-09-22 2016-09-23 2016-09-24 2016-09-25   2016-09-26 2016-09-27 2016-09-28 2016-09-29 2016-09-30 2016-10-01

预期输出

  

2016-09-01 2016-09-02 2016-09-03 2016-09-04 2016-09-05 2016-09-06   2016-09-07 2016-09-08 2016-09-09 2016-09-10 2016-09-11 2016-09-12   2016-09-13 2016-09-14 2016-09-15 2016-09-16 2016-09-17 2016-09-18   2016-09-19 2016-09-20 2016-09-21 2016-09-22 2016-09-23 2016-09-24   2016-09-25 2016-09-26 2016-09-27 2016-09-28 2016-09-29 2016-09-30                                                                                                                                               我不能使用 cal_days_in_month ,因为我有一个日期范围,必须计算所选日期之间的天数。

1 个答案:

答案 0 :(得分:0)

你真的很亲近。您只需要更改循环,以便在第一次迭代时$this_date等于$date_from1

变化:

$this_date=$date_from1->add(new DateInterval('P1D'));

要:

$this_date= $i? $date_from1->add(new DateInterval('P1D')): $date_from1;

旁注:您的代码很浪费,因为您多次创建具有相同值的new DateInterval。如果在循环之前创建一个日期间隔,则可以提高效率:

$interval = new DateInterval('P1D');

然后在循环的每次迭代中使用它:

$this_date= $i? $date_from1->add($interval): $date_from1;

Live demo

相关问题