2011-11-22 19 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()或直接拿到區別...