Thursday, 15 May 2014

php - How to loop through months that have been already passed -


I have low for loop through each month of the year, however, it starts leaving on February.

  $ start = new date time ('2015-01-01'); $ Start- & gt; Modify ('Last day of this month'); $ Current = new date time ('now'); $ End = new date time ('2018-01-01'); $ Interval = dateinline :: createFromDateString ('1 month'); $ Period = new date period ($ start, $ interval, $ end); $ Timestamp = array (); Foreign Currency ($ period $ dt) {$ dt-> Modify ('Last day of this month'); Echo 'C:' $ current-> Format ('df y'). '& Lt; Br> & # 39; & # 39; Echo 's:'. $ Start- & gt; Format ('df y'). '& Lt; Br> & # 39; & # 39; Echo 'D:' $ Dt-> Format ('df y'). '& Lt; Br> & # 39; & # 39; Echo & lt; Br> & Lt; Br> '; }  

However, the above output:

  C: 17 March 2015 S: 31 January 2015 D: January 31, 2015 C: 17 March 2015 S: 31 January 2015 D: 31 March 2015 C: March 17, 2015 S: 31 January 2015 D: April 30, 2015 Can someone see my mistake? I had the hope of keeping the value of  D  to  28 February 2015 . 

I just want a list of those months that have already been passed. / P>

update

The problem highlighted by MLeFevre in the comments is that working with the interval of the date can be difficult .

<<> see example # 3 date period , slightly like this Do not use the Modify method differently:

  $ current = new dateTime ('now'); $ End = new date time ('2018-01-01'); While ($ current> $ end) {$ current-> Modify ('Last day of next month'); Echo 'C:' $ current-> Format ('df y'). '& Lt; Br> & # 39; & # 39; }  

In your question, you are adding one month ago, then going to end of the month. This does not work, because the length of each month is different.

Sample output:

  C: 30 April 2015 C: 31 May 2015 C: 30 June 2015 C 31 July 2015 C: 31st August 2015 C: 31 October 2015 C : November 30, 2015 C: 30 November 2015 C: 31 December 2015 C: 31 January 2016 C: 29 February 2016 C: 31 March 2016 // From  

to $ start < To loop in / code> to $ current , you can change a little logic like this:

  $ Start = New date time ('2015-01 -31 '); // start from end of month $ current = new date time ('now'); Do {echo 'C:' $ Start-> Format ('df y'). '& Lt; Br> & # 39; & # 39; } While ($ start-> modify ('last day of next month') & lt; $ current);  

Output:

  C: January 31, 2015 C: 28 February 2015 

No comments:

Post a Comment