繁体   English   中英

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

[英]php or mysql list dates between range?

我需要生成一个日期列表(使用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表,但我需要完整的日期列表。

这样的事情应该这样做:

//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;

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

使用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";
}

资源

尝试这个:

<?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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM