JavaScript - - By Sam Deering

Calculate Twitter Time Since Tweet using JavaScript

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);
    if(sinceMin==0)
    {
        var sinceSec=Math.round((cTime-tTime)/1000);
        if(sinceSec<10)
          var since='less than 10 seconds ago';
        else if(sinceSec<20)
          var since='less than 20 seconds ago';
        else
          var since='half a minute ago';
    }
    else if(sinceMin==1)
    {
        var sinceSec=Math.round((cTime-tTime)/1000);
        if(sinceSec==30)
          var since='half a minute ago';
        else if(sinceSec<60)
          var since='less than a minute ago';
        else
          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);
    if(sinceHr==1)
      var since='about 1 hour ago';
    else
      var since='about '+sinceHr+' hours ago';
    }
    else if(sinceMin>1439&&sinceMin<2880)
        var since='1 day ago';
    else
    {
        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
setInterval(function()
{
    console.log('updating time since...');
    var tweets = $('#tweets .tweet');
    $.each(tweets, function(i,v)
    {
        //update the time since for the tweet
        $(v).find('.tweet-time').html(calculateSince($(v).find('.tweet-user').attr('created_at'))).fadeIn();
    });
}, 30000);
Sponsors