php getdate() vs date()

kpower picture kpower · Apr 9, 2011 · Viewed 24.2k times · Source

Theoretical question.

Imagine the situation. I need to get today date and time (not now, but today - the start of the day). I can do it with either this code:

$now = time();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now)));

or this:

$now = getdate();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, $now['mon'], $now['mday'], $now['year']));

In most examples I've seen, the first way is used. The question is simple: why? The first one uses 3 function calls more to get month, day and year.

Answer

Charles picture Charles · Apr 9, 2011

Both of those options are pretty horrible -- if you're trying to get the current date at midnight as a formatted string, it's as simple as:

date('Y-m-d') . ' 00:00:00';

Or, if you want to be slightly more explicit,

date('Y-m-d H:i:s', strtotime('today midnight'));

No need to do that wacky mktime thing. Whoever wrote that code does not know what they are doing and/or is a copy-paste/cargo-cult developer. If you really see that in "most examples," then the crowd you're hanging out with is deeply troubled and you should probably stop hanging out with them.

The only interesting thing that mktime does is attempt to work with the local timezone. If your work is timezone sensitive, and you're working with PHP 5.3 or better, consider working with DateTime and DateTimeZone instead. A demo from the PHP interactive prompt:

php > $utc = new DateTimeZone('UTC');
php > $pdt = new DateTimeZone('America/Los_Angeles');
php > $midnight_utc = new DateTime('today midnight', $utc);
php > $midnight_utc->setTimeZone($pdt);
php > echo $midnight_utc->format('Y-m-d H:i:s');
2011-04-08 17:00:00

(At the moment, it is the 9th in UTC, while it's the 8th in PDT.)