2010-08-20 141 views
2

我有兩個日期 - 開始日期和結束日期。我需要返回月份的數組(「YM」格式),其中包括起始和結束日期之間的每個月,還有幾個月,這些日期是在我已經試過:返回包含開始日期和結束日期的月數

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-09-15'); 
$month = $start; 
while($month <= $end) { 
    $months[] = date('Y-m', $month); 
    $month = strtotime("+1 month", $month); 
} 

的問題是在上面的例子中,它只將「2010-08」添加到數組中,而不是「2010-09」。我覺得解決方案應該是顯而易見的,但我看不到它。

請注意,這應該考慮到像帳戶情況:

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-08-21'); 
// should return '2010-08' 

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-09-01'); 
// should return '2010-08,2010-09' 

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-10-21'); 
// should return '2010-08,2010-09,2010-10' 

此外,PHP的我的主機上的版本是5.2.6,因此具有這些範圍內的工作。


我使用的解決方案是基於以下答案。設置$start到月份的第一天。然而,我不能僅僅使用strtotime(),而是必須使用我在網上找到的另一個功能。

function firstDayOfMonth($uts=null) 
{ 
    $today = is_null($uts) ? getDate() : getDate($uts); 
    $first_day = getdate(mktime(0,0,0,$today['mon'],1,$today['year'])); 
    return $first_day[0]; 
} 

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-09-15'); 
$month = firstDayOfMonth($start); 
while($month <= $end) { 
    $months[] = date('Y-m', $month); 
    $month = strtotime("+1 month", $month); 
} 

回答

2

的問題是,$開始一天比結束日大,所以你加入個月後開始其比結束大,解決方案是使用該月的第一天,像這樣2010-08-01後你加1個月,你會得到至少等於$ end;)

+0

我真的很想喜歡你的解決方案,因爲它的清潔/邏輯,當我使用'的strtotime(「這個月的第一天」,$月份)在我的Mac測試'它工作正常,返回'$ month'中定義的月份的第一天。但是當我在主機上完成同樣的事情時,它會返回1970-01-01。 – ggutenberg 2010-08-21 06:20:09

+1

這讓我走上了正軌。在問題中提供了完整的解決方案。 – ggutenberg 2010-08-21 10:11:27

0

這應該做你所需要的。

$start = strtotime('2010-08-20'); 
$end = strtotime('2010-10-15'); 
$month = $start; 
$months[] = date('Y-m', $start); 
while($month <= $end) { 
    $month = strtotime("+1 month", $month); 
    $months[] = date('Y-m', $month); 
} 
+0

這幾乎可以工作,但當$ start和$ end在同一個月時,它會崩潰。 – ggutenberg 2010-08-21 06:33:03

+0

它會以任何一種方式返回開始月份,只要$ start和$ end在同一個月內不會進入while,則數組月份只會包含$ start。試試print_r($ months);過了一段時間,你會看到。 – Centurion 2010-08-21 07:32:54

+0

使用'$ start = strtotime('2010-08-20')在PHP 5.3.1上進行本地測試; $ end = strtotime('2010-08-21');'在這種情況下,它仍然進入循環,增加'$ month'並且寫入第二個月到數組。 – ggutenberg 2010-08-21 07:52:24

0

環路下面添加

if(date('d',$month) != date('d',$end)) 
    $months[] = date('Y-m', $month); 

。這意味着,如果僅在$end(日期不同:最後差異小於一個月)中添加了最後一個月份

RBO

+0

當$ start和$ end在同一個月份時,這也會失敗。 – ggutenberg 2010-08-21 06:36:06

相關問題