Markus Hedlund

Developer / Photographer

Contact / GitHub / Instagram

Work With Me

Convert dates to elapsed time with Javascript

At Mimmin we know that every tiny detail can matter, and we always strive to simplify things and remove the unnecessary. This might be things like graying out certain parts of text to make others more evident.

A while ago I made a Javascript library that could convert absolute time to relative. This proved to be useful in many projects. When I implemented it in one of our latest projects I had to make some improvements. These changes made it to a patch, and now the official build is updated to version 1.1. Because of this I thought it would be good to make a small tutorial and show one way of using library.

Enhancing the readability of a log

One of the most useful things with this library is to convert absolute times (like 2009-01-10) into relative ones (like 6 weeks ago). I will in an example show how to convert a log with dates into one with relative dates.

Above you can see the expected result of this tutorial. The original dates will be converted to time elapsed. I will be using the excellent Javascript framework jQuery, but this is not necessary since the Countdown Library is framework independent.

The markup for the log list is a follows.

<ul id="log">
  <li class="added">
    <div>An item has been added</div>
    <div class="date">2009-01-19 13:58</div>
  </li>

  <li class="removed">
    <div>An item has been removed</div>
    <div class="date">2009-01-19 17:15</div>
  </li>
</ul>

We now want to, using Javascript, step through every div element with class "date" in the ul element "log". We will then replace the date value with a "time passed" value. But for those users that are looking for the absolute date, we are going to add it to the "title" attribute of the div. Code as follows.

$('#log div.date').each(function(){
  var date = $(this).text();
  $(this).
    html(
      remaining.getString(-remaining.getSeconds(date), null, true) + ' ago'
    ).attr('title', date);
});

First we save the date value. Then we replace it with the return value from remaining.getString. The return value from remaining.getSeconds(date) is inverted because the function calculates time remaining, and we want the time that has passed.

The second parameter to remaining.getString is an internationalization (i18n) object, which I didn't alter since the output should be in english.

The third parameter is a flag that controls if the output should be exact, or if it is enough with only the largest unit. Example output is "2 hours, 1 minute, 5 seconds" versus "2 hours".

At last we add the saved date to the attribute "title" of the div element. This is all that is needed folks! But don't forget to include the Countdown Library using the snippet below.

<script type="text/javascript" src="http://www.labs.mimmin.com/countdown/remaining.js"></script>

If you have any questions, please leave a comment →

2009-05-05