Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define distance in time in words in pure javascript?

I would like to include very common feature in my web application. I would like the times/dates be written as the distance of time from now in words, for example (2 hours ago).

Rails have excellent implementation of this functionality, but I need something like that written in pure javascript. The problem is, that lots of pages in my application are cached, and the only thing that would change is the actual time.

Are there any extended libraries in JS which could translate a date to a distance of time in words?

like image 660
mdrozdziel Avatar asked Dec 16 '10 12:12

mdrozdziel


2 Answers

The timeago plugin for jQuery works well.

From the example code:

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

Since you referenced using libraries, I'm assuming 'pure javascript' just means not anything on the server.

like image 99
Tim Lytle Avatar answered Sep 30 '22 15:09

Tim Lytle


If you don't want to use jQuery, you can use JavaScript Relative Time Helpers. It's an extension of the Date class, providing a handy toRelativeTime() method.

like image 35
Alexander Wallin Avatar answered Sep 30 '22 16:09

Alexander Wallin