Forum Moderators: coopster
I know this description is very general, but all of it does work (except for the format change I indicated I'm not sure how to do yet).
Just wondering if anybody knows of a more elegant solution. I'm not looking for "Here's the code", just more like "I know of this great little function or proceedure..."
Thanks in advance for any info.
$date1 = '2006-02-06';
$date2 = '2006-02-28';
for ($i = 0; $i < ((strtotime($date2) - strtotime($date1)) / 86400); $i++){
if(date('l',strtotime($date1) + ($i * 86400)) == 'Sunday'){
$num_sundays++;
}
}
echo "There are $num_sundays Sundays in that date range.\n";
"86400" is because that's 24 hours, and hence, "a day."
strtotime($later_date) - strtotime($earlier_date) should give you the total number of seconds between those two dates. Dividing that by 86400 should give you the number of days between those dates. (NOTE: this will ONLY work if you are using YYYY-MM-DD as the argument to strtotime() because it sets them both to 00:00:00 for the time and it will be exactly a multiple of 24 hours apart. If you also give it times, and the times are different, then you'll have to make sure to integerize the result of the division.)
In the loop, you move the date up by starting with $date1, and adding "$i * 86400" so that as $i goes up, the date goes up by one day/24 hours/86400 seconds.
Then, date('l',[timestamp]) (that's a letter "l" not a number one, btw) gives the full day of the week, so you just check it for "Sunday" in the loop.
Does that make sense?
I love strtotime(). :-)
I'm sure a PHP guru could give a better answer, and there may be something wrong with the above (PHP is not my first language), but it seemed to test out okay and give me the valid number of Sundays when I gave it different dates ...
JK
Yep, strtotime() is great!