解析Twitter API created_at

时间:2011-08-28 19:45:24

标签: php datetime twitter

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

  

Sun Aug 28 19:31:16 +0000 2011

进入这个:

  

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

1 个答案:

答案 0 :(得分:21)

如果您使用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'部分实际上是他们时区的每用户设置,而不是文字字符串。