grid calendar generator for php Updated

Posted by & filed under Uncategorized.

This one's simpler based on php 5.3 and more calendar functions 14 fewer lines and it's using timestamps for each grid square, so you can use the dates well for whatever other purposes.
function grid_cal($m){
   $bag = ""; 
   $m = strtotime("first day of this month",$m);
	$i = strtotime("-" . date("w",$m) . " days",$m); // starts on the previous sunday
	$bag .= "<table class=\"cal-table\"><tr class=\"cal-month\">\n<td colspan=\"7\">" .date("F",$m) ." ". date("Y",$m) . "</td>\n</tr>\n<tr class=\"cal-days\">";
	for($j=0;$j<7;$j++){
		$bag .= "\n<td>" . date("D",strtotime("+$j days",$i)) . "</td>";
	}
	$bag .="\n</tr>";
	while(!(date("m",$i)>date("m",$m) && date("w",$i)==0)){
		if(date("w",$i) == 0)
			$bag .= "\n<tr>";
		$bag .= (date("m",$i)==date("m",$m)) ? "\n<td>" . date("j",$i) . "</td>" : "<td class='emptygrid'></td>";
			
		if(date("w",$i) == 6)
			$bag .= "\n</tr>";
		
		$i = strtotime("+1 day",$i);
	}
	$bag .= "\n</table>";
	return $bag;
}
here's how you'd use it...
 print grid_cal(time());

4 Responses to “grid calendar generator for php Updated”

  1. Brandon

    I have been searching and searching for a snipplet like this one.. [not this version, the previous one.] that actually worked and did as I wanted.. — I was excited to see Updated version.. to bad its got a error. 🙁

    PHP Error Message

    Fatal error: Maximum execution time of 10 seconds exceeded in /home/a2870064/public_html/php-test/calendar-test2.php on line 17

    — This could be because of my FREE webhost.. not sure.. I’m just going by what it is saying… Any comments, suggestions?? Thanks in Advance.

  2. Scot

    Requires PHP 5.3 to work (“first day of” is introduced in PHP 5.3). This might be an issue.

    10 seconds is a short period to execute a script, but it should be long enough for these fast loops.

  3. Scot

    I can’t test it right now, but I think you could replace line 3 above with
    $m = strtotime(date(‘Y-m-01’,$m));

Leave a Reply