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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.