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

南楼画角 提交于 2019-12-03 23:03:53
Mike B
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.

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');

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!