Reputation: 686
Here is my problem all months start from day 1 but month 7 2012 start from day 2 don't know why
and here is the code
<table>
<?php
$cMonth = 7;
$cYear = 2012;
$first_day_timestamp = mktime(0,0,0,$cMonth,1,$cYear);
$maxday = date("t",$first_day_timestamp);
$thismonth = getdate($first_day_timestamp);
$startday = $thismonth['wday'] - 1;
for ($i=0; $i<($maxday+$startday); $i++) {
if (($i % 7) == 0 ) echo "<tr>";
if ($i < $startday) { echo "<td> </td>" ; continue; }
$current_day = $i - $startday + 1;
echo "<td>". $current_day . "</td>";
if (($i % 7) == 6 ) echo "</tr>";
}
?>
</table>
Image attached
Please tell me why this happened
Upvotes: 0
Views: 406
Reputation: 2966
Why are you doing this:
$startday = $thismonth['wday'] - 1;
??
You're moving the day offset back one. This is effectively saying the day you want to start counting on is one day before the first day of the month.
--EDIT-- So you're doing that because you want the calendar to start on Monday instead of Sunday. php's wday is this:
0 (for Sunday) through 6 (for Saturday)
You're subtracting one from it will shift the start of the month down one day until and unless the month starts on Sunday. Then $startday is -1 and it throws off your counting. You need it to wrap around to the previous week instead. If you add another line that fixes this case like:
$startday = thismonth['wday'] - 1;
if($startday < 0 ) $startday = 6;
It should fix the problem. I'm sure there's other ways to compensate for Monday being the first day of the week though.
Upvotes: 1
Reputation: 31141
Changing $startday = $thismonth['wday'] - 1;
to $startday = $thismonth['wday'];
displays the proper calendar with Sunday being the first day of the week.
The issue with your code is that $startday is -1 ($thismonth['wday'] is 0 since the month begins on a Sunday). In the first iteration of the loop, $current_day = 0 - (-1) + 1 = 2
so it starts at 2, which is correct, because Monday is the 2nd of the month.
You'll have this issue on any month that begins on a Sunday. Try September 2013.
Upvotes: 2