Jump to content

looping through days of current month


chiprivers

Recommended Posts

I am trying to create a loop that will work through the dates of the current month; I have the following piece of code for the loop:

 

$monthFloor = DateTime::createFromFormat('j H:i:s', '1 0:0:0');

$monthCeiling = DateTime::createFromFormat('j H:i:s', $monthFloor->format('t').' 0:0:0');

for (

$monthDate = DateTime::createFromFormat('Y-m-d H:i:s', $monthFloor->format('Y-m-d H:i:s')); 
$monthDate->format('d') <= $monthCeiling->format('d'); 
$monthDate->modify('+ 1 day')

) 

{

echo $monthDate->format('Y-m-d H:i:s')."<br />";

}

 

But when I run this, it loops through the dates of the current month twice!? why is it doing this? and how can I rectify the loop so it only goes through the month once?

Link to comment
https://forums.phpfreaks.com/topic/228647-looping-through-days-of-current-month/
Share on other sites

Hey Chip,

 

The problem in ur code lies in the following

$monthDate->format('d') <= $monthCeiling->format('d') ; 

 

What you are making an error with is only checking the day. Its currently doing this:

01 <= 28 true fire the statement and add the new day

02 <= 28 true fire the statement and add the new day

......

28<= 28 true fire the statement and add the new day

 

NOW as soon as it adds the day it rolls to the new month causing $monthDate->format('d') to return 0 doing this again :

01 <= 28 true fire the statement and add the new day

..

BUT because March has more than 28 days u finally get the line:

29 <= 28 False and it exits

 

In order to fix this change this:

$monthDate->format('d') <= $monthCeiling->format('d') ; 

to this:

$monthDate->format('Y-m-d') <= $monthCeiling->format('Y-m-d') ; 

 

Hope this helps ya.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.