Skip to main content

A function to return the relative time from date in JavaScript

var relativeTime = function (threshold) {
  var o = new Date();
  var k = new Date(threshold);

  if (navigator.userAgent.match(/MSIEs([^;]*)/)) {
    k = Date.parse(threshold.replace(/( +)/, " UTC$1"));
  }

  var n = o - k;
  var h = 1000,
    i = h * 60,
    j = i * 60,
    l = j * 24,
    g = l * 7;

  if (isNaN(n) || n < 0) {
    return "";
  }

  if (n < h * 2) {
    return "right now";
  }
  if (n < i) {
    return Math.floor(n / h) + " seconds ago";
  }
  if (n < i * 2) {
    return "about 1 minute ago";
  }
  if (n < j) {
    return Math.floor(n / i) + " minutes ago";
  }
  if (n < j * 2) {
    return "about 1 hour ago";
  }
  if (n < l) {
    return Math.floor(n / j) + " hours ago";
  }
  if (n > l && n < l * 2) {
    return "yesterday";
  }

  if (n < l * 365) {
    return Math.floor(n / l) + " days ago";
  } else {
    return "over a year ago";
  }
};

var mydate = new Date("2/2/2011");
var lastupdated = relativeTime(mydate);
console.log('Posted ' + lastupdated);