簡體   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