Calculate Twitter Time Since Tweet using JavaScript

By Sam Deering

This script calculates the “Twitter time” since the tweet was created this is returned from the Twitter REST API search.json in a property called ‘created_at’ (example: “Tue, 12 Jun 2012 06:24:59 +0000”). This function could be used to display the “time since” tweeted on say a Twittter Widget or such and then you could use a setInterval to refresh the time since tweeted (see below for example).

The calculateSince function()

  * Calculates the Twitter time since the tweet was created
  * @param datetime returned by Twitter API in created_at
  * @return time since in html
function calculateSince(datetime)
    var tTime=new Date(datetime);
    var cTime=new Date();
    var sinceMin=Math.round((cTime-tTime)/60000);
        var sinceSec=Math.round((cTime-tTime)/1000);
          var since='less than 10 seconds ago';
        else if(sinceSec<20)
          var since='less than 20 seconds ago';
          var since='half a minute ago';
    else if(sinceMin==1)
        var sinceSec=Math.round((cTime-tTime)/1000);
          var since='half a minute ago';
        else if(sinceSec<60)
          var since='less than a minute ago';
          var since='1 minute ago';
    else if(sinceMin<45)
        var since=sinceMin+' minutes ago';
    else if(sinceMin>44&&sinceMin<60)
        var since='about 1 hour ago';
    else if(sinceMin<1440){
        var sinceHr=Math.round(sinceMin/60);
      var since='about 1 hour ago';
      var since='about '+sinceHr+' hours ago';
    else if(sinceMin>1439&&sinceMin<2880)
        var since='1 day ago';
        var sinceDay=Math.round(sinceMin/1440);
        var since=sinceDay+' days ago';
    return since;

Refresh the Time Since Tweeted

This is how you could use a setInterval to refresh the time since tweeted using the calculateSince function above.

//auto refresh interval to load more tweets
    console.log('updating time since...');
    var tweets = $('#tweets .tweet');
    $.each(tweets, function(i,v)
        //update the time since for the tweet
}, 30000);

No Reader comments



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.