簡體   English   中英

強制php strtotime使用UTC

[英]force php strtotime to use UTC

我已經看到了一些關於這個的問題,但不是一個明確的答案......當將字符串轉換為unix時間戳時,strtotime()將使用為PHP設置的默認時區。

但是,我想將字符串轉換為UTC中的unix時間戳。 由於沒有這樣做的參數,怎么辦呢?

我想要轉換的字符串是:2011-10-27T20:23:39,已經是UTC了。 我想將其表示為UTC中的unix時間戳。

謝謝

我意識到這個問題已經很老了,但我找到了另一個可能有用的選項。 您可以將時區指定為傳遞給strtotime的字符串的一部分,而不是設置然后還原php的時區,如下所示:

echo date_default_timezone_get();
output: America/Chicago

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39'));
output: 2011-10-28 01:23:39

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39 America/Chicago'));
output: 2011-10-28 01:23:39

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39 UTC'));
output 2011-10-27 20:23:39

注意:我在PHP 5.5.9上,但這應該適用於任何PHP版本。

在進行strtotime調用之前設置系統默認時區:

date_default_timezone_set('UTC');
echo strtotime('2011-10-27T20:23:39')."\n";

// Proof:
print_r(getdate(strtotime('2011-10-27T20:23:39')));

// IMPORTANT: It's possible that you will want to
// restore the previous system timezone value here.
// It would need to have been saved with
// date_default_timezone_get().

看到它在行動

其他兩個答案都很好。 由於我有同樣的問題,我想提供第三種選擇。

$utc = new DateTimeZone('UTC');
$dt = new DateTime('2011-10-27T20:23:39', $utc);
var_dump($dt->format('U'));

string(10) "1319747019"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM