我需要生成一個日期列表(無論是PHP或MySQL或兩者),我有一個指定的開始和結束日期?例如,如果開始日期是2012-03-31並且結束日期是2012-04-05我怎樣才能生成這樣的列表?PHP或MySQL列表日期之間的範圍?
2012-03-31
2012-04-01
2012-04-02
2012-04-03
2012-04-04
2012-04-05
我有一個mysql表的開始和結束日期,但我需要的日期的完整列表。
我需要生成一個日期列表(無論是PHP或MySQL或兩者),我有一個指定的開始和結束日期?例如,如果開始日期是2012-03-31並且結束日期是2012-04-05我怎樣才能生成這樣的列表?PHP或MySQL列表日期之間的範圍?
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
// 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);
使用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";
}
什麼是您的DB時間戳的格式? – Xfile 2012-03-31 15:32:14