2013-06-23 107 views
-1

我想返回特定範圍之間的所有天數。
我的想法是,通過將它們添加86400(一天秒),開始和結束日期,以Unix時間戳和循環轉換:循環遍歷天

<?php 
    $start = strtotime('2013-01-01'); 
    $end = strtotime('2013-02-01'); 

    for($i=$start; $i<=$end; $i+86400) 
    { 
    echo date("l, d.m.y", $i) . "\n"; 
    } 
?> 

不幸的是,我只得到當日內:

Tuesday, 01.01.13 
Tuesday, 01.01.13 
Tuesday, 01.01.13 
... 
+0

運營商錯誤。試試'$ i + = 86400'而不是'$ i + 86400'。當你在它的時候,切換到[DateTime對象](http://us.php.net/manual/en/datetime.add.php)並明確添加「1天」而不是「86400秒」。 – DCoder

+0

@DCoder ['DatePeriod'](http://php.net/dateperiod)是爲這種類型的任務而創建的。 – salathe

+1

如果你想分配一些值,你需要一個代理運算符:http://www.php.net/language.operators.assignment - 如果你想迭代一些東西,你應該像http:// php .net/dateperiod;) - 同時注意不是所有的日子都有86400秒。只是說,不是你認爲如此。 – hakre

回答

5

這是錯誤的:

for($i=$start; $i<=$end; $i+86400) 

應該

for($i=$start; $i<=$end; $i+=86400) 

請注意您原始代碼的++=插入。在你的代碼中,你沒有給變量賦新值,只是執行沒有結果的數學公式

+0

作爲備註$ i + = 86400是$ i = $ i + 86400的簡寫代碼 – exussum

+0

注意:從備用時間切換到夏令時或其他方式或添加閏秒等時會造成問題,更好地使用salathe的方法 – johannes

7

最好的做法是使用DatePeriod類。

$start = new DateTime('2013-01-01'); 
$end = new DateTime('2013-02-01'); 

foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $date) { 
    echo $date->format("l, d.m.y\n"); 
} 
+0

如果你不想使用DatePeriod,你也有'$ next_day = strtotime('+ 1 day',$ current_stamp)',但同意'DatePeriod'是最佳實踐。 – bnlucas