PHP Calendar Functions

It’s really easy to get really mixed up when trying to program with date functions – lots to keep track of, calendars, timezones, daylight saving, weird months that have different numbers of days in them…

Here’s a quick rundown on the main PHP functions involved.

1. checkdate()

bool checkdate ( int $month , int $day , int $year )

Does just what it says, for the Gregorian calendar, and it’s been around since PHP4 – a very quick way to ensure that the programming isn’t coming up with any silly results. Always useful!

2.. date() and gmdate()

From a given UNIX timestamp, date() tells you what time would be in your server timezone and gmdate() tells you what GMT it would be (or UTC, the same thing…). It is important to get the hang of the consequences of this and one way of figuring it out is to bear in mind the date() format character “Z” – the timezone offset in seconds, positive or negative.

No matter what the timezone is set to, these 2 expressions will produce the same result…

<?php
	date_default_timezone_set('America/Montreal');

	echo date("Y/m/d H:i:s",(time()));
	echo gmdate("Y/m/d H:i:s",(time()+ date("Z")));

?>

3. strtotime()

Takes a string and should return a Unix timestamp.

It does say string in “US English date format” – which means that for strtotime (“04/06/2010″) is April 6th, and not the 4th of June. (Probably no need to get into a discussion about the relative logic of the two systems here).

strtotime has a pretty decent understanding of language – so you can do relative times:

strtotime('next Monday');
strtotime('+1 years');
strtotime('first day next month');
strtotime('2010-02 last day');

All return what you’d expect, based on the datetime the function’s run…

4. mktime()

Good for catching “overflows”.

echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 2009)) // => Jan-01-2010 
echo date("M-d-Y", mktime(0, 0, 0, 15, 31, 2009)) // => Mar-31-2010 

Like strtotime, mktime doesn’t go in unit magnitude order – it’s hours, minutes, seconds, months, days, years…. why? because that’s the decision that was made…

Find a birth day with mktime:-

	$my_birthdate = mktime(0,0,0,5,12,72);
	print date("l", $my_birthdate);
	//gives:   Friday

A Few More Calendar Tricks

Current age

<?php  echo floor(abs(strtotime('Y') - strtotime('02/22/1968'))/31536000);  ?>

Easter date

<?php echo date("M-d-Y", easter_date(2010));   ?>     // Apr-04-2010

Datetime constants
PHP 5.1 and later, via the DateTime class, offers a few shorthand formatting strings.

<?php echo date(DATE_RSS); ?>
//gives something like: Thu, 21 Feb 2010 09:35:44 -0800

The defined strings are here – also good for cookies.

Daylight Saving Problems
One way of cutting out possible problems with daylight saving time differences across timezones is to work in UTC, using expressions like these (and then revert back to a local timezone at the end if necessary).

date_default_timezone_set('UTC');
 
$date_utc = strtotime($date. " UTC");