views:

67

answers:

2

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.

  • 1 minute ago
  • 1 hour ago
  • 1 day ago
  • 1 month ago
  • 1 year ago
+6  A: 
function timeSince(date) {

    var seconds = Math.floor((new Date() - date) / 1000);

    var interval = Math.floor(seconds / 31536000);

    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}
Sky Sanders
I just added this to my snippets library. +1 for the poet
Marko
+1 for not using ridiculous nested if-elses.
Hello71
@hello - yeah, single point of exit has it's virtues when it doesn't get in the way. those that take it too seriously these days are misunderstanding the origin of the maxim.
Sky Sanders
+5  A: 

I haven't checked (although it wouldn't be hard to), but I think that Stack Exchange sites use the jquery.timeago plugin to create these time strings.


It's quite easy to use the plugin, and it's clean and updates automatically.

Here's a quick sample (from the plugin's home page):

First, load jQuery and the plugin:

<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script>

Now, let's attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago(); });

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">about a year ago</abbr> which yields: about a year ago. As time passes, the timestamps will automatically update.

Maxim Zaslavsky
+ thanks for that. i deleted a comment regarding the lack of a jquery tag on this question, but really, what does it matter? peace.
Sky Sanders