我怎样才能在php中获得一系列日期?

时间:2012-01-24 17:05:31

标签: php

$start_date = '2012-01-01';
$end_date = '2012-12-31';
$total_days = round(abs(strtotime($end_date) - strtotime($start_date)) / 86400, 0) + 1;

if ($end_date >= $start_date)
{
  for ($day = 0; $day < $total_days; $day++)
  {
    echo "<br />" . date("Y-m-d", strtotime("{$start_date} + {day} days"));
  }
}

现在正在一遍又一遍地打印'1969-12-31'。预期的输出应为:

2012-01-01
2012-01-02
2012-01-03
...
2012-12-30
2012-12-31

3 个答案:

答案 0 :(得分:6)

我会使用DatePeriod课程(以及DateTimeDateInterval):

$start_date = '2012-01-01';
$end_date = '2012-12-31';

$start    = new DateTime($start_date);
$end      = new DateTime($end_date);
$interval = new DateInterval('P1D'); // 1 day interval
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $day) {
    // Do stuff with each $day...
    echo $day->format('Y-m-d'), "\n";
}

答案 1 :(得分:1)

上面的代码可以使用一个额外的字符 - 你在这一行错过了$

echo "<br />" . date("Y-m-d", strtotime("{$start_date} + {$day} days"));
//                                                        ^ This was missing

答案 2 :(得分:0)

<?php

$start_date = '2012-01-01';
$end_date = '2012-12-31';
$total_days = round(abs(strtotime($end_date) - strtotime($start_date)) / 86400, 0) + 1;

if ($end_date >= $start_date)
{
  for ($day = 0; $day < $total_days; $day++)
  {
    echo "<br />" . date("Y-m-d", strtotime("{$start_date} + {$day} days"));
                                 //     You missed the $ here ^
  }
}
相关问题