Erik A. Hanson's Weblog

Relative dates in Javascript

Posted: December 4th, 2008    Tags: Javascript

A while ago, I posted some Javascript code that produces a nice relative date string (e.g., “4 days ago” or “18 minutes ago”) given two dates.

I looked at the code again and noticed that it was pretty long and needlessly required Prototype. So I cleaned it up a bit:

/**
 * Simple relative date.
 *
 * Returns a string like "4 days ago". Prefers to return values >= 2. For example, it would
 * return "26 hours ago" instead of "1 day ago", but would return "2 days ago" instead of
 * "49 hours ago".
 *
 * Copyright (c) 2008 Erik Hanson http://www.eahanson.com/
 * Licensed under the MIT License http://www.opensource.org/licenses/mit-license.php
 */
function relativeDate(olderDate, newerDate) {
  if (typeof olderDate == "string") olderDate = new Date(olderDate);
  if (typeof newerDate == "string") newerDate = new Date(newerDate);

  var milliseconds = newerDate - olderDate;

  var conversions = [
    ["years", 31518720000],
    ["months", 2626560000 /* assumes there are 30.4 days in a month */],
    ["days", 86400000],
    ["hours", 3600000],
    ["minutes", 60000],
    ["seconds", 1000]
  ];

  for (var i = 0; i < conversions.length; i++) {
    var result = Math.floor(milliseconds / conversions[i][1]);
    if (result >= 2) {
      return result + " " + conversions[i][0] + " ago";
    }
  }

  return "1 second ago";
}

Try it out:

Older date:


Newer date:

Relative date:   (Update)

Raw code and tests:
relativeDate.js
relativeDateTest.html



3 Responses to “Relative dates in Javascript”

  1. Ayke van Laethem Says:

    Thanks!

    One correction: when the olderDate is a string, this is needed (see the parseInt):
    if (typeof olderDate == “string”) olderDate = new Date(parseInt(olderDate));
    otherwise it won’t work (or am I supposed to do something different?)

  2. Erik Says:

    The code is assuming that if it’s a string, it’s already human-formatted and needs to be parsed. So if the date is “Sun Apr 10 2011″, then “new Date(‘Sun Apr 10 2011′)” will parse the string and create the correct date.

    I assume that you have the situation where you have a string representing the number of milliseconds since 1970, such as “1302418800000″. In that case, you definitely would have to parse the int.

  3. Ayke van Laethem Says:

    I have used this code in a Chrome extension. See https://github.com/aykevl93/Chrome-Sync.

Leave a Reply



(Comments are moderated to keep out spam. Please be patient.)