Php getdate () vs date ()

The theoretical question.

Imagine a situation. I need to get the date and time (not now, but today is the beginning of the day). I can do this with 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 that:

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

Most of the examples I've seen use the first method. The question is simple: why? The first uses 3 function calls more to get the month, day, and year.

+5
source share
1 answer

Both of these options are pretty terrible - if you try to get the current date at midnight as a formatted string, it is as simple as:

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

Or, if you want to be a little more explicit,

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

mktime. , , , , / / . " ", , , , , , .

, mktime, . , PHP 5.3 , DateTime DateTimeZone. PHP:

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

( 9- UTC, - PDT.)

+13

All Articles