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
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.
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";
}
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 oftimeago
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.