Format Twitter time created_at

Twitter statuses comes in the usual retrievable ugly format

1
Sun Jul 03 16:11:11 +0000 2011

From this, its hard to tell whether it was 5 minutes ago or 5 hours ago.
What we need to do is get the time right now and find out how long ago it is from this time.

1
2
3
4
function from_apachedate($date){
    list($D,$M,$d,$h,$m,$s,$y) = sscanf($date, "%s %s %2d %2d:%2d:%2d +0000 %4d");
    return strtotime("$d $M $y $h:$m:$s");
}

Before I get credit for this, I found this from another site (NOTE : it was broken, and I nicely notified the owner of my fix).

What the function above does is return the twitter time in UNIX format. Take what is returned and run it through the function below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function elapsedtime($time){
    $gap = time()- $time;
                           
   if ($gap < 60)
        return $gap.' seconds ago';
    $gap = round($gap / 60);
    if ($gap < 60)
        return $gap.' minute'.($gap > 1 ? "s" : "").' ago';
    $gap = round($gap / 60);
    if ($gap < 24)
        return 'about '.$gap.' hour'.($gap > 1 ? "s" : "").' ago';
    $gap = round($gap / 24);
    if ($gap > 24)
        return round($gap).' days ago';
        return date('h:i A F d, Y', $time);
}

This function was a whole 16 characters smaller than the smallest function I could find… I know it’s not much, but it’s for those fellow kilobyte crunchers :) .

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>