Home » Php » php – Parsing The Twitter API created_at

php – Parsing The Twitter API created_at

Posted by: admin July 12, 2020 Leave a comment


I want to parse the Twitter API created_at value(stored into a variable), which looks like this:

Sun Aug 28 19:31:16 +0000 2011

Into this:

19:31, Aug 28

But I need it to be timezone-aware. Any ideas about how to make this using php?

After using the second option which John Flatness suggested I’m getting this error:

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
How to&Answers:

If you set the timezone you want to output in with date_default_timezone_set (or the date.timezone INI setting), you can simply do:

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

If you instead need to potentially output in many different time zones, it’s probably easier to use the new-style DateTime class:

$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');

Obviously the 'America/New_York' part would actually be a per-user setting for their timezone, not a literal string.