How to get current date/time as a date object in PHP

McGarnagle picture McGarnagle · Jun 12, 2012 · Viewed 49.4k times · Source

How do you get today's date, as a date object?

I'm trying to compute the difference between some start date and today. The following will not work, because getdate() returns an array and not a date object:

$today = getdate();           
$start = date_create('06/20/2012');
$diff = date_diff($start, $today);

echo($today . '<br/>' . $start . '<br/>' . $diff);

Output:

Array ( [seconds] => 8 [minutes] => 1 [hours] => 16 [mday] => 11 [wday] => 1 [mon] => 6 [year] => 2012 [yday] => 162 [weekday] => Monday [month] => June [0] => 1339455668 )

DateTime Object ( [date] => 2012-06-20 00:00:00 [timezone_type] => 3 [timezone] => America/Los_Angeles )

Answer

Mike B picture Mike B · Jun 12, 2012
new DateTime('now');

http://www.php.net/manual/en/datetime.construct.php

Comparing is easy:

$today = new DateTime('now');
$newYear = new DateTime('2012-01-01');

if ($today > $newYear) {

}

Op's edit I just needed to call date_default_timezone_set, and then this code worked for me.