22
votes

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 )

3

3 Answers

46
votes
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.

16
votes

To get difference in days use this:

$today = new DateTime('today');

the time in this object eill be 00:00:00

If you want difference with hours minutes and seconds use this:

$now = new DateTime('now');
0
votes

I ended up using the date_create constructor (no parameter) to get the current date.

$diff = date_diff(date_create('06/20/2012'), date_create());
print_r($diff);

Output:

DateInterval Object ( [y] => 0 [m] => 0 [d] => 8 [h] => 6 [i] => 30 [s] => 40 [invert] => 1 [days] => 8 )

I have no idea why, but Mike B's answer (and any constructor I tried for DateTime) threw an error for me in PHP5 / IIS.