如何在PHP中获取当前日期/时间作为日期对象 [英] how to get current date/time as a date object in PHP

查看:91
本文介绍了如何在PHP中获取当前日期/时间作为日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取今天的日期作为日期对象?

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

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

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

输出:


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

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

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

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


推荐答案

新的DateTime('now');

new DateTime('now');

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

比较简单:

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

if ($today > $newYear) {

}

Op的编辑
我只需要调用 date_default_timezone_set ,然后这段代码为我工作。

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

这篇关于如何在PHP中获取当前日期/时间作为日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆