将带有时区的日期字符串转换为时间戳


Convert date string with timezone to timestamp

我收到以下格式的日期2015-01-09T20:46:00+0100,需要将其转换为时间戳。不幸的是,strtotime函数忽略了时区组件:

print strtotime('2015-01-09T20:46:00+0100') . "'n";
print strtotime('2015-01-09T20:46:00');
//result is the same with or without timezone:
//1420832760
//1420832760

解决这个问题的正确方法是什么?

DateTime 可以正确处理此问题:

$date = new DateTime('2015-01-09T20:46:00+0100');
echo $date->getTimestamp();
echo "'n";
$date = new DateTime('2015-01-09T20:46:00');
echo $date->getTimestamp();
1420832760
1420836360

演示

我弄清楚了!

使用默认时区,除非在该时区中指定了时区 参数 http://php.net/manual/en/function.strtotime.php

这就是为什么结果是相同的设置或不是时区:

date_default_timezone_set('Europe/Paris');
print strtotime('2015-01-09T20:46:00+0200');
print "'n";
print strtotime('2015-01-09T20:46:00+0100');
print "'n";
print strtotime('2015-01-09T20:46:00');
print "'n'n";
date_default_timezone_set('UTC');
print strtotime('2015-01-09T20:46:00+0100');
print "'n";
print strtotime('2015-01-09T20:46:00');

输出:

1420829160
1420832760
1420832760
1420832760
1420836360

演示:https://eval.in/241781

感谢您的帮助!