【问题标题】:Convert date string with timezone to timestamp将带有时区的日期字符串转换为时间戳
【发布时间】:2015-01-13 14:06:40
【问题描述】:

我收到以下格式的日期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

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

【问题讨论】:

  • 如果它与java有关希望这可能会有所帮助stackoverflow.com/questions/2891361/…>
  • 你可能可以这样做$date = new DateTime('2015-01-09T20:46:00+0100'); echo $date->format('Y-m-d H:i:s');

标签: php date timezone


【解决方案1】:

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

Demo

【讨论】:

  • 大声笑,为什么这在我的本地主机上不起作用?我首先虽然 DateTime 也可以工作,但是在我的 XAMPP localhost 服务器上它不起作用,你知道吗?
  • 老实说,我不知道。最好的猜测是一个 php 版本的错误。你运行的是什么版本的 PHP?
  • 我的 PHP 版本是:5.5.6,我在 ideone.comeval.in 上尝试过它,它成功了,现在我厌倦了它:3v4l.org,它没有工作看这里: 3v4l.org/cYnDG,好像真的很奇怪
  • 我认为这应该行不通!因为查看手册->参数->注释并阅读注释! php.net/manual/en/datetime.construct.php
  • 对我来说也一样。 DateTime 方法和 strtotime 都适用于 eval.in 但不适用于我的本地 WAMP (php 5.5.8)
【解决方案2】:

我想通了!

使用默认时区,除非指定时区 范围 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

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2023-03-17
    • 1970-01-01
    • 2017-09-08
    • 2011-03-19
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多