7

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
Community
  • 1
  • 1
Nathan Campos
  • 28,769
  • 59
  • 194
  • 300
  • 1
    You can pass the timezone as the second argument to the `DateTime` constructor to prevent that error (or set the date.timezone setting in php.ini or use `date_default_timezone_set` to explicitly set a default timezone). – John Flatness Aug 28 '11 at 20:51

1 Answers1

21

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.

John Flatness
  • 32,469
  • 5
  • 79
  • 81
  • Is there anyway to get the timezone at the client? – Nathan Campos Aug 28 '11 at 19:54
  • 1
    I've added an alternative method that may be a better choice if you're going to be needing to output in many different timezones. As for detecting the user's timezone, that's really a different question, but as said in http://stackoverflow.com/questions/5203382/how-to-automatically-detect-users-timezone, you can really only make a rough guess of your user's timezone. You're likely better off just asking them upfront and storing that information. – John Flatness Aug 28 '11 at 20:03