I want to compare a date (like Tue, 04 Nov 2014 04:02:59 -0800) with the current date and display as below:
a few seconds ago
10 minutes ago
2 days ago
1 month ago
etc.
What is the most efficient way to do this in JavaScript/jQuery?
I've created something that might be useful.
function timeAgo(dateString){
var postDate = new Date(dateString),
now = new Date(),
dif = now - postDate, // ms
s = Math.floor(dif/1000),
m = Math.floor(s/60),
h = Math.floor(m/60),
d = Math.floor(h/24),
M = now.getMonth() - postDate.getMonth(),
y = new Date(dif).getFullYear() - 1970,
t = ["year","month","day","hour","minute","second"],
a = [y,M,d,h,m,s];
for(var i in a) if(a[i]) {a=a[i]; t=t[i]; break;}
return a +" "+ (a>1?t+"s":t) +" ago";
}
alert("This post was created "+ timeAgo("Tue, 04 Nov 2014 16:44:07 +0100") );
Returns this examples
6 seconds ago
1 minute ago
9 hours ago
12 days ago
1 month ago
2 years ago
If you're already using jQuery, I'd recommend taking a look at Moment.js. It's the best date library I've been able to find so far. You can take advantage of the fromNow() function which will give you the output you're looking for.
var data = '',
date = new Date();
date.setYear(2012);
data += moment(date).fromNow() + "<br />";
date.setYear(2016);
data += moment(date).fromNow() + "<br />";
date.setYear(2014);
data += moment(date).fromNow() + "<br />";
$('#output').html(data);
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='output'></div>
"-1 for not showing any attempt to solve your own problem"please, know that new users might not know exactly what's a -1 and neither how to properly format a Question. Have patience and point OP to the right direction :)