【问题标题】:Parsing The Twitter API created_at解析 Twitter API created_at
【发布时间】:2015-12-07 18:51:01
【问题描述】:

我要解析 Twitter API created_at 值(存储到变量中),如下所示:

2011 年 8 月 28 日星期日 19:31:16 +0000

进入这个:

8 月 28 日 19:31

但我需要它能够识别时区。关于如何使用php 进行此操作的任何想法?


使用John Flatness 建议的第二个选项后,我收到此错误:

Fatal error:  Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Sao_Paulo' for 'BRT/-3.0/no DST' instead' in /misc.php:4
Stack trace:
#0 /misc.php(4): DateTime->__construct('Sun Aug 28 19:3...')
#1 /tabs/home.php(29): format_date(Object(SimpleXMLElement), 'America/Sao_Pau...')
#2 {main}
  thrown in /misc.php on line 4

【问题讨论】:

  • 您可以将时区作为第二个参数传递给 DateTime 构造函数以防止出现该错误(或在 php.ini 中设置 date.timezone 设置或使用 date_default_timezone_set 显式设置默认时区)。

标签: php datetime twitter


【解决方案1】:

如果您使用date_default_timezone_set(或 date.timezone INI 设置)设置要输出的时区,您可以这样做:

$formatted_date = date('H:i, M d', strtotime('Sun Aug 28 19:31:16 +0000 2011'));

如果您需要在许多不同的时区进行潜在输出,则使用新式DateTime 类可能更容易:

$date = new DateTime('Sun Aug 28 19:31:16 +0000 2011');
$date->setTimezone(new DateTimeZone('America/New_York'));
$formatted_date = $date->format('H:i, M d');

显然,'America/New_York' 部分实际上是每个用户的时区设置,而不是文字字符串。

【讨论】:

  • 有没有办法在客户端获取时区?
  • 我添加了一种替代方法,如果您需要在许多不同的时区输出,这可能是更好的选择。至于检测用户的时区,这确实是一个不同的问题,但正如stackoverflow.com/questions/5203382/… 所说,您实际上只能粗略猜测用户的时区。您最好提前询问他们并存储这些信息。
猜你喜欢
  • 1970-01-01
  • 2017-07-13
  • 2014-10-10
  • 1970-01-01
  • 2021-04-06
  • 2012-11-09
  • 2013-12-07
  • 1970-01-01
  • 2016-03-01
相关资源
最近更新 更多