2016-07-12 2 views
2

Hier ich einige Frage in PHP Datumwie kann ich die Schleife vom Startdatum Enddatum laufen für alle 3 Monate in php

-Code

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

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

So, jetzt haben, was im Versuch, i müssen sie als Quatar aufzuspalten, die für alle 3 Monate bedeutet

Erwartetes Ergebnis

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 

Gibt es einen einfachen Weg, um das Ergebnis zu erzielen?

+0

Beschreibung ist verwirrend –

Antwort

1

Die Klassen DateTime und DateInterval sind leistungsstarke Tools, um die Frage zu lösen, und Sie müssen sich nicht um die Anzahl der Tage in jedem Monat kümmern.

// 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); 
Verwandte Themen