Update time descriptions every minute using jquery/javascript
- by Amy Neville
I have created the following code to update the text contents of all spans like this every minute. There are numerous of these spans on the page which all need to be updated every minute:
<span unix="1372263005" class="time_ago">4 minutes ago</span>
The code is as follows:
window.setInterval(function(){
var unix = $(".time_ago").text();
var now = new Date().getTime();
var amount = 0;
var difference = 0;
difference = now - parseInt(unix);
if (difference < 60)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">a few seconds ago</span>');
}
else if (difference < 120)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">a minute ago</span>');
}
else if (difference < 3600)
{
amount = floor(difference / 60);
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">' + amount + ' minutes ago</span>');
}
else if (difference < 7200)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">an hour ago</span>');
}
else if (difference < 86400)
{
amount = floor(difference / 3600);
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">' + amount + ' hours ago</span>');
}
else if (difference < 172800)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">a day ago</span>');
}
else if (difference < 2635200)
{
amount = floor(difference / 86400);
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">' + amount + ' days ago</span>');
}
else if (difference < 5270400)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">a month ago</span>');
}
else if (difference < 31622400)
{
amount = floor(difference / 2635200);
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">' + amount + ' months ago</span>');
}
else if (difference < 63244800)
{
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">a year ago</span>');
}
else (difference >= 63244800)
{
amount = floor(difference / 31622400);
$(".time_ago").text('<span unix="' + unix + '" class="time_ago">' + amount + ' years ago</span>');
}
return false;
}, 60);
EDIT) Ok, now I have made some changes on your advice but it's changing the span texts to 43351 years. Any ideas why it is doing that?