chiprivers Posted February 23, 2011 Share Posted February 23, 2011 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 More sharing options...
mhodge_txs Posted February 24, 2011 Share Posted February 24, 2011 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 https://forums.phpfreaks.com/topic/228647-looping-through-days-of-current-month/#findComment-1179045 Share on other sites More sharing options...
chiprivers Posted March 3, 2011 Author Share Posted March 3, 2011 Thanks. All sorted now. I did resolve the issue but had not worked out why it wasn't working originally. Simple now you point it out!! Link to comment https://forums.phpfreaks.com/topic/228647-looping-through-days-of-current-month/#findComment-1182251 Share on other sites More sharing options...
mhodge_txs Posted March 3, 2011 Share Posted March 3, 2011 Cool man glad you all sorted Link to comment https://forums.phpfreaks.com/topic/228647-looping-through-days-of-current-month/#findComment-1182258 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.