简体   繁体   English

强制php strtotime使用UTC

[英]force php strtotime to use UTC

I've seen a few questions about this but not a clear answer... strtotime() will use the default timezone set for PHP when converting the string to a unix timestamp. 我已经看到了一些关于这个的问题,但不是一个明确的答案......当将字符串转换为unix时间戳时,strtotime()将使用为PHP设置的默认时区。

However, I want to convert a string to unix timestamp in UTC. 但是,我想将字符串转换为UTC中的unix时间戳。 Since there is no parameter for doing so, how can this be done? 由于没有这样做的参数,怎么办呢?

The string I'm trying to convert is: 2011-10-27T20:23:39, which is already in UTC. 我想要转换的字符串是:2011-10-27T20:23:39,已经是UTC了。 I want to represent that as a unix timestamp also in UTC. 我想将其表示为UTC中的unix时间戳。

Thank you 谢谢

I realize this question is very old, but I found another option that can be helpful. 我意识到这个问题已经很老了,但我找到了另一个可能有用的选项。 Instead of setting and then reverting php's time zone, you can specify the timezone as a part of the string you pass to strtotime like so: 您可以将时区指定为传递给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

Note: I am on PHP 5.5.9, but this should work in any php version. 注意:我在PHP 5.5.9上,但这应该适用于任何PHP版本。

Set the system default timezone before making the strtotime call: 在进行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().

See it in action . 看到它在行动

Both other answers are really fine. 其他两个答案都很好。 As I have the same issue, I want to offer a third option. 由于我有同样的问题,我想提供第三种选择。

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

gives string(10) "1319747019" string(10) "1319747019"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM