Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  76] [ 2]  / answers: 1 / hits: 107270  / 13 Years ago, tue, may 24, 2011, 12:00:00

I'm looking for a nice JS snippet to convert a timestamp (e.g. from Twitter API) to a nice user friendly relative time (e.g. 2 seconds ago, one week ago etc).



Anyone care to share some of their favourite methods (preferably not using plugins)?


More From » datetime

 Answers
5

Well it's pretty easy if you aren't overly concerned with accuracy. What wrong with the trivial method?



function timeDifference(current, previous) {

var msPerMinute = 60 * 1000;
var msPerHour = msPerMinute * 60;
var msPerDay = msPerHour * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;

var elapsed = current - previous;

if (elapsed < msPerMinute) {
return Math.round(elapsed/1000) + ' seconds ago';
}

else if (elapsed < msPerHour) {
return Math.round(elapsed/msPerMinute) + ' minutes ago';
}

else if (elapsed < msPerDay ) {
return Math.round(elapsed/msPerHour ) + ' hours ago';
}

else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago';
}

else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago';
}

else {
return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago';
}
}


Working example here.



You might want to tweak it to handle the singular values better (e.g. 1 day instead of 1 days) if that bothers you.


[#92085] Sunday, May 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;