如何在 PHP 中获取当前日期/时间作为日期对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10988625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:32:27  来源:igfitidea点击:

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

phpdatedatediff

提问by McGarnagle

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:

我正在尝试计算某个开始日期和今天之间的差异。以下将不起作用,因为getdate()返回一个数组而不是日期对象:

$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 )

数组 ( [seconds] => 8 [minutes] => 1 [hours] => 16 [mday] => 11 [wday] => 1 [mon] => 6 [year] => 2012 [yday] => 162 [工作日] => 星期一 [月] => 六月 [0] => 1339455668)

日期时间对象( [date] => 2012-06-20 00:00:00 [timezone_type] => 3 [timezone] => America/Los_Angeles)

回答by Mike B

new DateTime('now');

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

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 editI just needed to call date_default_timezone_set, and then this code worked for me.

Op 的编辑我只需要调用date_default_timezone_set,然后这段代码对我有用

回答by Skipper

To get difference in days use this:

要获得天数差异,请使用以下命令:

$today = new DateTime('today');

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

此对象中的时间为 00:00:00

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

如果您想要时分和秒的差异,请使用以下命令:

$now = new DateTime('now');

回答by McGarnagle

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

我最终使用date_create构造函数(无参数)来获取当前日期。

$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 )

DateInterval 对象 ( [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.

我不知道为什么,但 Mike B 的回答(以及我为DateTime尝试的任何构造函数)在 PHP5/IIS 中为我​​抛出了一个错误。