Early Christmas Present - Javascript Relative Time
So today - instead of shopping and getting in the holiday sprit - I coded. Why? Well because its fun. I ran into an issue that I though I would share. Currently - I'm working a social networking site than run their own home grown Twitter Application. I wanted it to be in a real time - and adjust the timestamps as it performs an AJAX call to see if there any new messages.
I searched near and far for the best javascript relative time - but I couldn't find the best one that I liked. Finally - found one done by Tutorialize, that they used for a Twitter Ticker. I changed it a bit to be able to display the correct date in the format that i wanted and edited the number of days allowed to be displayed before it reverts back to the regular timestamp.
So behold - a early christmas present from Santa "javascript" Claus - I hope that you find good use for it. It's a bit scrappy - but I would like to hear your comments and feedback.
Merry Christmas!
// usage
var rel = relativeTime("Thu, 24 Dec 2009 09:45:33 -0800");
// returns
"One Hour Ago"
// code
function relativeTime(pastTime)
{
var origStamp = Date.parse(pastTime);
var cDate = new Date();
var currentStamp = cDate.getTime();
var difference = parseInt((currentStamp - origStamp)/1000);
if(difference < 0) return false;
if(difference <= 5) return "Just now";
if(difference <= 20) return "Just Seconds ago";
if(difference <= 60) return "A minute ago";
if(difference < 3600) return parseInt(difference/60)+" minutes ago";
if(difference <= 1.5*3600) return "One hour ago";
if(difference < 23.5*3600) return Math.round(difference/3600)+" hours ago";
if(difference < 1.5*24*3600) return "One day ago";
var days = difference / (1.5*24*3600);
if (days <= 10)
{
return Math.round(days) + " days ago";
}
else
{
var dateArr = pastTime.split(' ');
var t = dateArr[4].split(":");
var time_format = "";
if (parseInt(t[0]) > 12)
{
var a = parseInt(t) - 12
time_format = dateArr[2] + " " + dateArr[1] + " " + a + ":" + t[1] + " PM";
}
else
{
var first = "";
if (t[0].substring(0, 1) == "0")
{
first = t[0].substring(1, 2);
}
else
{
first = t[0];
}
time_format = dateArr[2] + " " + dateArr[1] + " " + first + ":" + t[1] + " AM";
}
return time_format;
}
}
