PHP's getdate() functionPosted in PHP -
I've been coding PHP since 1999 and I'm still discovering functions I didn't know about. Just the other day I read someone's post about some useful PHP functions and I knew all of them except for the getdate() function so I thought I'd cover it here.
PHP has the very useful date() function for formatting dates and times which I use frequently myself but often find myself doing something like this if I need both the year and the month:
$month = date('j'); // day of the month without leading zeroes $year = date('Y'); // 4 digit year
That's not the most efficient way of doing things, especially if you need to get some other variables as well, because it's making multiple calls to the date() function. Enter the getdate() function.
Calling getdate() without parameters will use the current date and time and assign the various variables to an associative array like so:
$date = getdate(); print_r($date);
The above outputs this:
Array ( [seconds] => 55 [minutes] => 41 [hours] => 11 [mday] => 19 [wday] => 0 [mon] => 4 [year] => 2009 [yday] => 108 [weekday] => Sunday [month] => April  => 1240098115 )
You can also specify a timestamp if you had your date in that format already (or by converting it using the strtortime() function). The following example uses the timestamp for midnight on April 1st 2009:
$date = getdate(1238497200); print_r($date);
And the output:
Array ( [seconds] => 0 [minutes] => 0 [hours] => 0 [mday] => 1 [wday] => 3 [mon] => 4 [year] => 2009 [yday] => 90 [weekday] => Wednesday [month] => April  => 1238497200 )
Going back to the example at the start of this post, I could now do this instead of calling date() multiple times:
$date = getdate(); ... $date['mon'] ...; ... $date['year'] ...;