The PHP getdate Function

Another useful date/time function is getdate. This will return an array (associative) with all the date and time values. You can use it for things like comparing one date to another. For example, comparing how many days have passed since a given date. Here’s the syntax:

getdate( time_stamp );

The time stamp is optional. If you leave it out, it gets the values for the current local date and time. The parts of the array are this:

seconds 
minutes 
hours
mday (day of the month as a number)
wday (day of the week as a number)
mon (month a number)
year 
yday (year day as a number)
weekday (day in text format)
month (month in text format)
0 (Seconds since the Unix Epoch)

Because getdate returns an associative array, you can just do this sort of thing:

$today = getdate();
print $today['mday'];
print $today['wday'];
print $today['yday'];

So whichever part of the array you want to access goes between square brackets. You then type one of the above Keys between quote marks.

As a further example, suppose you want to work out how many days it’s been since a forum member last posted something. And that you have used this to write the date of the last post in a database:

$post_date = date('z');

Now, you’ve read this value back in, and you want to compare that date against today’s date. You can do it like this:

<?PHP

$post_date = 60;
$today = getdate();

$day_difference = $today['yday'] - $post_date;

Print "Days since last post = " . $day_difference;

?>

So we’ve set up the array using getdate:

$today = getdate();

We’ve then used “yday” to calculate how many days have elapsed since the last post:

$day_difference = $today['yday'] - $post_date;

Working with dates and times can be quite tricky, and a good reference is the PHP.net website. As well as setting out all the date and time functions, there’s lots of posts from people with good date/time scripts:

http://uk.php.net/manual/en/function.date.php