-3

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?

9
  • Checkout the answer here should help you out stackoverflow.com/a/16465436/1370442 Commented Nov 4, 2014 at 14:06
  • @bUKaneer I think that question is the reverse of this one. OP there are plenty of plugins that will do this, E.g: timeago.yarp.com Commented Nov 4, 2014 at 14:07
  • 1
    Another plugin which I really like is MomentJS, by far the most advanced plugin I have found. Supports lots of languages too: momentjs.com Commented Nov 4, 2014 at 14:10
  • 1
    -1 for not showing any attempt to solve your own problem Commented Nov 4, 2014 at 14:16
  • @DevlshOne "-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 :) Commented Nov 4, 2014 at 15:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Take a look at the fiddle

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.