How to change date formate of twitter field “created_at”?

php coder who is reading twitter API for latest tweets want to change date/ timestamp format which is returned by ‘created_at’ key. Most of the times I use JSON based request. e. i. http://search.twitter.com/search.json?q=phpmind

These are the fields returned by above request.

Hope fully you understand how json string looks like.

Now it is time to convert date time stamp in more readable format.

echo date("l M j \- g:ia",strtotime($object->returns[0]->created_at));

Please change the date parameters if you want to play with different date formats.

If you want to use javaScript way to format dates here is very cool function.
Returned by twitter – Wed, 09 Feb 2011 02:44:36 +0000

Returned by this javaScript function, TwitterDateConverter ($object->returns[0]->created_at);
Output will be for Example “14 minutes ago”

See Image Below!


function Convert_Datetime($datetime)
{
    define("SECOND", 1);
    define("MINUTE", 60 * SECOND);
    define("HOUR", 60 * MINUTE); define("DAY", 24 * HOUR);
    define("MONTH", 30 * DAY); $delta = time() - strtotime($datetime);

    // convert

    if($delta < 1 * MINUTE)
    {
        return $delta == 1 ? "one second ago" : $delta." seconds ago";
    }
    if($delta < 2 * MINUTE)
    { return "a minute ago";
    }
    if($delta < 45 * MINUTE)
    {
        return floor($delta / MINUTE)." minutes ago";
    }
    if($delta < 90 * MINUTE)
    {
        return "an hour ago";
    }
    if($delta < 24 * HOUR)
    {
        return floor($delta / HOUR)." hours ago";
    }
    if($delta < 48 * HOUR)
    {
        return "yesterday";
    }
    if($delta < 30 * DAY)
    {
        return floor($delta / DAY)." days ago";
    }
    if($delta < 12 * MONTH)
    {
        $months = floor($delta / DAY / 30); return $months <= 1 ? "one month ago" : $months." months ago"; }
    else
    {
        $years = floor($delta / DAY / 365); return $years <= 1 ? "one year ago" : $years." years ago";
    }

echo Convert_Datetime("2015-04-1 22:10:00"); // one year ago

Share

2 thoughts on “How to change date formate of twitter field “created_at”?

  1. Imran Ashraf

    Thanks for sharing function. JS code converts date within a month only. Old dates(more than 4 months) are shown like “undefined”.

    can this function be modified for this as well for old dates?

  2. Pingback: Tweets that mention Twitter field date formatting “created_at” -- Topsy.com

Leave a Reply

Your email address will not be published. Required fields are marked *