2013-08-07 67 views
0

這是使用DateTime獲取PHP中當前時間的正確方法嗎?DateTime中的當前時間PHP

$currenttime = new DateTime(); 
$currenttime2 = $currenttime->format('H:i:s'); 
+3

恩,你試過嗎?它看起來正確嗎? –

+1

你可能想用'date_default_timezone_set(「America/New York」);'或者你的時區是什麼來作爲它的前綴。除此之外它應該沒問題。 http://php.net/manual/en/function.date-default-timezone-set.php –

+0

是它正確的方式,'新的DateTime();' – 2013-08-07 19:22:35

回答

1

我相信你可以做這樣的

$date = date('Y-m-d H:i:s'); 
+0

但那不是DateTime的權利?因爲我需要將它與另一個DateTime()對象進行比較... – nshah

+1

如果您想比較,那麼您必須使用$ currenttime,不要重新創建$ currenttime2,因爲這是一個字符串,而不是一個對象。 $ currenttime = new DateTime();使用當前時間創建一個DateTime對象作爲默認值。 – kwolfe

+0

好的,謝謝! – nshah

0

這將設置基於在php.ini的日期時間設置的時間。在創建後執行$ currenttime的var_dump以查看我的意思。你也可以使用microtime(true);獲取可以使用其他函數轉換的unix時間戳。