php检查指定的时间是否已过期

时间:2011-11-22 15:09:29

标签: php mysql

我正在尝试使用字符串将当前日期时间与数据库中的日期时间进行比较,如下所示:

$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s'); 

if($todayString >= $rows["PrioritizationDueDate"])
{...}

$todayString不断给我7小时的时间(即现在是晚上11点03分,给我16:04)。

更多,比较这种方式更好,还是应该使用日期时间对象进行比较?

3 个答案:

答案 0 :(得分:1)

  

$ todayString让我在7小时前给我时间

你必须为我相信的DateTime对象设置一个时区。

  

以这种方式比较更好

我对此表示怀疑 一般的方法是在查询中进行比较,使用SQL进行所有日期计算并仅返回匹配的行。

答案 1 :(得分:0)

在构造函数中将正确的时区设置为DateTime。

$today = new DateTime("now", new DateTimeZone('TimezoneString'));

TimezoneStringvalid timezone string

修改:有关使用DateTime对象的更完整示例,我会将DateTime::diffDateTime::createFromFormat结合使用。

$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';

$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));

if( $row_date->diff( $today)->format('%a') > 1)
{
    echo 'The row timestamp is more than one day in the past from now.';
}

Demo

答案 2 :(得分:0)

首先使用此功能设置时区

 date_default_timezone_set('UTC');

然后你可以使用函数strtotime()或直接得到差异......

相关问题