Formatting Twitter’s Date/Time With PHP

Posted: August 18th, 2010 | Author: | Filed under: Tips/Tutorials
Tags: , , , , ,

This should save you a little googling. When you look at the XML that the Twitter API gives you, each tweet has a ‘created_at‘ timestamp.

It looks like this: Wed Aug 18 18:22:29 +0000 2010. Not too friendly, but it’s really simple to convert it to a unix timestamp, then format it with PHP’s date function.

Step 1: Make the unix timestamp with strtotime(). Now it’s turned into 1282155749, which is just what we need even though it looks worse.

Step 2: Format with date(). ‘l M j \- g:ia‘ turns it into ‘Wednesday Aug 18 – 12:22pm‘. You have total control of how it looks thanks to that date() function of PHP.

I pretty much dumped it all into a single line on one of the things I was working on. This is after I retrieved the XML into a variable called $xml.

echo date("l M j \- g:ia",strtotime($xml->status[0]->created_at));
Last Modified: August 18th, 2010


9 Comments on “Formatting Twitter’s Date/Time With PHP”

  1. 1 Kym Dusting said at 2:28 am on September 30th, 2010:

    Beautiful! Thanks.

  2. 2 Mikkis said at 2:00 pm on November 17th, 2010:

    Thank you! That’s good tip.

  3. 3 Jon said at 9:18 am on March 26th, 2011:

    Allstar :) Cheers!!

  4. 4 Elendurwen said at 9:16 am on August 12th, 2012:

    I used your method but the time is not right, for some reason date(“d/m/Y g:ia”,strtotime($obj[$var]->created_at)); returns time -4 hours from the created_at string. Any thoughts on that?

  5. 5 kn00tcn said at 2:04 pm on August 12th, 2012:

    @Elendurwen not sure… wonder if it’s something to do with your host, you could just add 4 hours to it i guess (or maybe there’s a time zone function)

  6. 6 Hero said at 9:21 am on April 9th, 2013:

    Thanks ……

  7. 7 Alex said at 7:22 pm on September 3rd, 2013:

    You are now required to make use the date.timezone setting or the date_default_timezone_set() function in PHP, so this may need updating slightly.

  8. 8 kn00tcn said at 5:16 am on September 4th, 2013:

    @Alex i also have to update the retrieval of tweets since the API changed, i found a nice WP plugin so that made me even lazier

  9. 9 Ajay Maurya said at 2:56 am on September 30th, 2014:

    For converting it into MySQL Datetime Format

    $modified_date = date(“Y-m-d H:i:s”, strtotime($date));

Leave a Reply