2011-06-12 28 views
0

好的說,我有兩個時間戳以格式yyyymmdd保存在數據庫中,一個開始日期和結束日期。兩個日期戳,在每一天之間響應

說的這些都是我的開始和結束日期:20110618-20110630

我怎麼會讓它回聲20110618,20110619,20110620等一路20110630?

回答

2
// Will return the number of days between the two dates passed in 
function count_days($a, $b) { 
    // First we need to break these dates into their constituent parts: 
    $gd_a = getdate($a); 
    $gd_b = getdate($b); 

    // Now recreate these timestamps, based upon noon on each day 
    // The specific time doesn't matter but it must be the same each day 
    $a_new = mktime(12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year']); 
    $b_new = mktime(12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year']); 

    // Subtract these two numbers and divide by the number of seconds in a 
    // day. Round the result since crossing over a daylight savings time 
    // barrier will cause this time to be off by an hour or two. 
    return round(abs($a_new - $b_new)/86400); 
} 

// Prepare a few dates 
$date1 = strtotime('20110618'); 
$date2 = strtotime('20110630'); 

// Calculate the differences, they should be 43 & 11353 
echo "<p>There are ", count_days($date1, $date2), " days.</p>\n"; 
$days = count_days($date1, $date2); 
for ($i = 0; $i < $days; $i++) { 
    echo date('Ymd', $date1+(86400*$i)); 
} 

從使用功能:Get number of days between two dates

+1

這種方法真是令人費解 - 使用[DateTime](http://stackoverflow.com/questions/6319388/two-date-stamps-echo-每天的事情/ 6319445#6319445) – 2011-10-09 11:45:42

+0

+1贊同....... – 2011-10-09 19:38:47

1

使用PHP DateTime對象,所以下面將是persudo代碼

//Convert the 2 dates to a php datetime object 
//Get the number of days differance inbetween 
//For each day, 
     //create a new datetime object, N days after the youngest object 
     //Echo the reasult out 
+0

那些都是假評論,我相信。如果存在這樣的事情。 ;) – 2011-06-12 00:48:55

+0

哈哈,對不起壞習慣。我傾向於這樣做,複製粘貼它,並輸入它的實際代碼 – PicoCreator 2011-06-12 01:03:10

0

你就不能這樣做: (編輯以包括實際的PHP環路)

$date = new DateTime('20110618'); 
do { 
    $d = $date->format('Ymd') . "\n"; 
    echo $d; 
    $date->add(new DateInterval('P1D')); 
} while ($d < 20110630); 
2

這應該打印的所有日期爲您在PHP 5.3

$start = '20110618'; 
$end = '20110630'; 

$date = new DateTime($start); 
$end = new DateTime($end)->getTimestamp(); 

while ($date->getTimestamp() <= $end) { 
    echo $date->format('Ymd'); 
    $date->add(new DateInterval('P1D')); 
} 
相關問題