php或mysql列表范围之间的日期?

时间:2012-03-31 15:23:46

标签: php mysql

我需要生成一个日期列表(使用php或mysql或两者),其中我指定了开始日期和结束日期?例如,如果开始日期是2012-03-31,结束日期是2012-04-05,我该如何生成这样的列表?

2012-03-31
2012-04-01
2012-04-02
2012-04-03
2012-04-04
2012-04-05

我有一个带有开始和结束日期的mysql表,但我需要完整的日期列表。

3 个答案:

答案 0 :(得分:1)

这样的事情应该这样做:

//Get start date and end date from database

$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$date_list = array($start_date);

$current_time = $start_time;

while($current_time < $end_time) {
    //Add one day
    $current_time += 86400;
    $date_list[] = date('Y-m-d',$current_time);
}
//Finally add end date to list, array contains all dates in order
$date_list[] = $end_date;

基本上,将日期转换为时间戳并在每个循环上添加一天。

答案 1 :(得分:1)

使用PHP的DateTime库:

<?php

$start_str = '2012-03-31';
$end_str = '2012-04-05';

$start = new DateTime($start_str);
$end = new DateTime($end_str . ' +1 day'); // note that the end date is excluded from a DatePeriod

foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $day) {
        echo $day->format('Y-m-d'), "\n";
}

Source

答案 2 :(得分:0)

试试这个:

<?php

  // Set the start and current date
  $start = $date = '2012-03-31';

  // Set the end date
  $end = '2012-04-05';

  // Set the initial increment value
  $i = 0;

  // The array to store the dates
  $dates = array();

  // While the current date is not the end, and while the start is not later than the end, add the next day to the array    
  while ($date != $end && $start <= $end)
  {
    $dates[] = $date = date('Y-m-d', strtotime($start . ' + ' . $i++ . ' day'));
  }

  // Output the list of dates
  print_r($dates);