2011-11-22 52 views
1

我想比较当前日期时间,与使用字符串数据库中的日期时间,如下所示:PHP的检查,如果指定的时间已过期

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

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

$todayString一直给我的时间为7小时前(即现在是11点03分,它给了我16点04分)。

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

+0

尝试时间戳其更容易比较 –

+0

您可能位于格林威治标准时间东部7小时? – Thilo

回答

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

1

$ todayString一直给我的时间为7小时前

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

更愿意到这样

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

0

首先设定时区使用此功能

date_default_timezone_set('UTC'); 

然后要么你可以使用函数的strtotime()或直接拿到区别...

相关问题