Design & Download
Your JS Library
in Seconds!!!

Snippet: getTimeAgo() - Relative Time Strings

Written by Christopher West (cwest) on November 23, 2015.
Indicates how long ago a specific date was.
function getTimeAgo(dateTime, opt_currDateTime) {
  opt_currDateTime = new Date(opt_currDateTime || new Date) - new Date(dateTime);
  return '31536e6year2592e6month864e5day36e5hour6e4minute1e3second'.replace(/(\d+e\d)([a-z]+)/g, function(m, ms, interval) {
    if (dateTime != undefined) {
      ms = Math.round(opt_currDateTime / +ms);
      if (ms >= 1 || interval == 'second') {
        dateTime = undefined;
        return ms + ' ' + interval + (ms - 1 ? 's' : '') + ' ago';
    return '';
  }) || undefined;

At times you may stumble across sites which indicate how long ago some piece of content was created or edited. This function is used by some to accomplish this task in PHP. In JavaScript we have this YourJS snippet which allows us to basically do the same thing.

getTimeAgo(...) API Documentation


Indicates how long ago a specified date was.


  1. dateTime {Date|number}:
    The Date or number (milliseconds since midnight January 1, 1970) representing the date/time that we want to compare to the current time.
  2. opt_currDateTime {Date|number}:
    Optional. Defaults to the current date/time. The Date or number (milliseconds since midnight January 1, 1970) used as the current time.


Returns a string indicating how many years or months or days or hours or minutes or seconds dateTime is ahead of opt_currDateTime. Eg. "5 minutes ago"