2012-03-11 32 views
1

我試圖得到以毫秒爲單位的時間差。PHP的奇怪行爲DateTime類

$_SESSION['startTime'] = time(); 
$to_time = time(); 

//I call the code from here after a delay, say 4 seconds 

$from_time = $_SESSION['startTime']; 
$d1 = new DateTime($from_time); 
$d2 = new DateTime($to_time); 


print_r($d1->diff($d2)); 

我打印結果4秒鐘後,結果是有點像這樣:

DateInterval Object 
(
    [y] => 4 //---- Problem, this value should be + 
    [m] => 0 //         | 
    [d] => 0 //         | 
    [h] => 0 //         |  
    [i] => 0 //         | 
    [s] => 0 //<-here-----------------------------+ 
    [invert] => 1 
    [days] => 1461 
) 

[S]應該已經4.爲什麼4是一年中的部分? 我在做什麼錯?

UPDATE - 解決

$to_time = (microtime(true)); 
$from_time = ($_SESSION['startTime']); 
$diff = $to_time - $from_time; 
print $diff; 

打印

3.xxxxxx 
+8

如果你已經有2個UNIX時間戳,爲什麼不直接相減?另外,如果你正在尋找毫秒精度,你需要microtime()。 – Corbin 2012-03-11 09:54:12

回答

3

您必須指定格式。你發送的Unix時間戳爲日期時間,爲此:

$d1 = new DateTime($from_time); 
$d2 = new DateTime($to_time); 

變爲

$d1 = new DateTime('@'.$from_time); 
$d2 = new DateTime('@'.$to_time); 

符號@告訴我使用的是UNIX時間戳日期時間。

+0

從來沒有聽說過這種語法。它也會帶來致命的錯誤。你有哪個版本的PHP?我有5.3.8 – 2012-03-11 10:31:16

+0

我正在使用5.3.10。它給出了什麼錯誤? – DanRedux 2012-03-11 10:35:01

+0

好吧,@Corbin的答案實際上解決了我的問題。 那麼,我正在使用microtime(true)並存儲在會話變量中。將來自會話變量的值與'@'符號組合會產生錯誤。 – 2012-03-11 10:45:11

0

constructor for DateTime接受一個字符串作爲參數而不是時間戳,這就是爲什麼你看到「奇怪的行爲」。

您需要明確設置時間戳insantiating一個DateTime對象後: -

$from_time = $_SESSION['startTime']; 
$d1 = new DateTime(); 
$d1->setTimestamp($from_time);