Question User Question User - 1 year ago 69
SQL Question

how can i run the loop from start date to end date for every 3 months in php

Here i have some question in php date


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

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

So now what im trying is i need to split it as quatar that means for every 3 months

Expected Result

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

Is there have any simple way to achieve the result ?

Answer Source

Classes DateTime and DateInterval are powerful tools to solve the question and you don't have to care about amount of days in each month.

// 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;
    $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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download