2016-07-12 18 views
2

在這裏,我有一些問題在PHP日期如何運行從開始日期到結束日期的循環,每3個月PHP

代碼

$calcdateloops = date("Y-m-01", strtotime(date('Y-m-d')." -1 year -6 Month")); //2015-01-01 

$enddate = date('Y-m-d'); 

所以現在我嘗試的是我需要將其拆分爲quatar這意味着對於每3個月

預期結果

1) 2015-01-01 - 2015-03-30 // first loop 
2) 2015-04-01 - 2015-06-30 
3) 2015-07-01 - 2015-09-30 
.... so on upto the end date 

是否有任何簡單的方法來實現結果?

+0

描述令人困惑 –

回答

1

DateTimeDateInterval是解決問題的強大工具,您不必關心每個月的天數。

// constructor accepts all the formats from strtotime function 
$startdate = new DateTime('first day of this month - 18 months'); 
// without a value it returns current date 
$enddate = new DateTime(); 

// all possible formats for DateInterval are in manual 
// but basically you need to start with P indicating period 
// and then number of days, months, seconds etc 
$interval = new DateInterval('P3M'); 

do { 
    // without clone statement it will copy variables by reference 
    // meaning that all you variables points to the same object 
    $periodstart = clone $startdate; 
    $startdate->add($interval); 
    $periodend = clone $startdate; 
    // just subtract one day in order to prevent intersection of start 
    // and end dates from different periods 
    $periodend->sub(new DateInterval('P1D')); 

    echo 'start: ', $periodstart->format('Y-m-d'), ', ', 'end: ', $periodend->format('Y-m-d'), '<br>'; 
} while ($startdate < $enddate); 
相關問題