将带时区的日期字符串转换为时间戳
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
我吓坏了!
uses the default time zone unless a time zone is specified in that
parameter
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
感谢您的帮助!
我收到以下格式的日期 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
我吓坏了!
uses the default time zone unless a time zone is specified in that parameter 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
感谢您的帮助!