Emmanuel Akinfulubi

JavaScriptBasic

Format relative time like 5 minutes ago in JavaScript

Intermediate · 3 min read

Social feeds, chat apps and comment sections rarely show an exact time. They say "just now", "5 minutes ago" or "yesterday". People read those faster than "15 January 2026, 11:55", and for a feed, a rough idea is all they need.

In this tutorial you will write ago(then, now), which turns the gap between two moments into that kind of label. You'll get "1 minute" versus "2 minutes" right, and handle a timestamp that is a little in the future, which happens more than you'd think. You need to know functions, if and how to create a date.

Subtracting dates

When you subtract one date from another, JavaScript gives you the gap in milliseconds (thousandths of a second). Divide by 1000 for seconds:

JavaScript

const now = new Date(2026, 0, 15, 12, 0, 0);
const then = new Date(2026, 0, 15, 11, 55, 0);
console.log(now - then);                // 300000
console.log(Math.round((now - then) / 1000)); // 300: five minutes in seconds

From seconds, it's all division: 60 seconds in a minute, 60 minutes in an hour, 24 hours in a day.

Why pass "now" in?

The function could call new Date() itself to get the current time. But then its answer changes every second, and you could never write a test that says "5 minutes ago". Passing now in as an argument means you can pin it to any moment you like. The real page just passes new Date().

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

131 Say how long ago that was, in words

fair

Turn the gap between two moments into the kind of label a feed shows: just now, 5 minutes ago, yesterday, 3 days ago. Take the current moment as an argument, get the singular right, and do something sensible when the timestamp is in the future.

Stuck? Three hints, smallest first
  1. 1. Work in seconds, and pick the largest unit whose count is at least one.
  2. 2. One is the only singular, so the plural is a suffix decided by the count.
  3. 3. A negative gap is not an error. Servers and phones disagree about the time.

Step 1: singular and plural

Only the number 1 takes the singular: "1 minute", but "0 minutes", "2 minutes". A tiny helper handles that once:

Step 1

const count = (n, unit) => n + ' ' + unit + (n === 1 ? '' : 's');
console.log(count(1, 'minute')); // 1 minute
console.log(count(3, 'hour'));   // 3 hours

Step 2: pick the largest unit that fits

Try minutes first. If there are 60 or more, switch to hours, then days, then months, then years:

Step 2

const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const count = (n, unit) => n + ' ' + unit + (n === 1 ? '' : 's');
function spell(seconds) {
  const minutes = Math.round(seconds / MINUTE);
  if (minutes < 60) return count(minutes, 'minute');
  const hours = Math.round(seconds / HOUR);
  if (hours < 24) return count(hours, 'hour');
  const days = Math.round(seconds / DAY);
  if (days < 30) return count(days, 'day');
  const months = Math.round(days / 30);
  if (months < 12) return count(months, 'month');
  return count(Math.round(days / 365), 'year');
}
console.log(spell(150));        // 3 minutes
console.log(spell(3 * HOUR));   // 3 hours
console.log(spell(29 * DAY));   // 29 days
console.log(spell(40 * DAY));   // 1 month
console.log(spell(400 * DAY));  // 1 year

The constants are in seconds, so HOUR is 3600 and DAY is 86400. Naming them makes 3 * HOUR easy to read.

Math.round rounds to the nearest whole number, so 150 seconds (two and a half minutes) reads as "3 minutes", and 59.6 minutes rounds to 60 and moves up to "1 hour". A month is counted as 30 days. That isn't exact, but nobody reading a feed is counting.

Step 3: "just now" and "ago"

Step 3

const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const count = (n, unit) => n + ' ' + unit + (n === 1 ? '' : 's');
function spell(seconds) {
  const minutes = Math.round(seconds / MINUTE);
  if (minutes < 60) return count(minutes, 'minute');
  const hours = Math.round(seconds / HOUR);
  if (hours < 24) return count(hours, 'hour');
  const days = Math.round(seconds / DAY);
  if (days < 30) return count(days, 'day');
  const months = Math.round(days / 30);
  if (months < 12) return count(months, 'month');
  return count(Math.round(days / 365), 'year');
}
function ago(then, now) {
  const seconds = Math.round((now - then) / 1000);
  if (Math.abs(seconds) < 45) return 'just now';
  if (seconds >= DAY && seconds < 2 * DAY) return 'yesterday';
  return spell(seconds) + ' ago';
}
const NOW = new Date(2026, 0, 15, 12, 0, 0);
const secondsBefore = (s) => new Date(NOW.getTime() - s * 1000);
console.log(ago(secondsBefore(5), NOW));        // just now
console.log(ago(secondsBefore(60), NOW));       // 1 minute ago
console.log(ago(secondsBefore(25 * HOUR), NOW)); // yesterday
console.log(ago(secondsBefore(3 * DAY), NOW));  // 3 days ago
console.log(ago(new Date(NOW.getTime() + 5 * MINUTE * 1000), NOW)); // -5 minutes ago

Anything under 45 seconds becomes "just now", because "12 seconds ago" is noise. A gap between one and two days reads as "yesterday". getTime() gives a date as milliseconds, which makes it easy to build test moments a few seconds before NOW.

The last line shows a gap: a timestamp five minutes in the future prints "-5 minutes ago".

Step 4: timestamps from the future

That sounds impossible, but it's common. Phone and computer clocks drift, and a post saved using the phone's clock can arrive at a server whose clock is a few seconds behind. Treat a negative gap as "in ...":

Step 4

const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const count = (n, unit) => n + ' ' + unit + (n === 1 ? '' : 's');
function spell(seconds) {
  const minutes = Math.round(seconds / MINUTE);
  if (minutes < 60) return count(minutes, 'minute');
  const hours = Math.round(seconds / HOUR);
  if (hours < 24) return count(hours, 'hour');
  const days = Math.round(seconds / DAY);
  if (days < 30) return count(days, 'day');
  const months = Math.round(days / 30);
  if (months < 12) return count(months, 'month');
  return count(Math.round(days / 365), 'year');
}
function ago(then, now) {
  const seconds = Math.round((now - then) / 1000);
  if (Math.abs(seconds) < 45) return 'just now';
  if (seconds < 0) return 'in ' + spell(-seconds);
  if (seconds >= DAY && seconds < 2 * DAY) return 'yesterday';
  return spell(seconds) + ' ago';
}
const NOW = new Date(2026, 0, 15, 12, 0, 0);
console.log(ago(new Date(NOW.getTime() + 5 * MINUTE * 1000), NOW)); // in 5 minutes
console.log(ago(new Date(NOW.getTime() + 10 * 1000), NOW));         // just now

-seconds flips the negative gap back to positive before spelling it. And because "just now" uses Math.abs, small clock differences in either direction are hidden.

The full solution

The answer panel has count, spell and ago, with the clock pinned to 15 January 2026 at noon. It prints the label for six gaps, from 5 seconds to 40 days. Press Run to see the output.

The answer

const MINUTE = 60;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;

const count = (n, unit) => n + ' ' + unit + (n === 1 ? '' : 's');

function spell(seconds) {
  const minutes = Math.round(seconds / MINUTE);
  if (minutes < 60) return count(minutes, 'minute');
  const hours = Math.round(seconds / HOUR);
  if (hours < 24) return count(hours, 'hour');
  const days = Math.round(seconds / DAY);
  if (days < 30) return count(days, 'day');
  const months = Math.round(days / 30);
  if (months < 12) return count(months, 'month');
  return count(Math.round(days / 365), 'year');
}

function ago(then, now) {
  const seconds = Math.round((now - then) / 1000);
  if (Math.abs(seconds) < 45) return 'just now';
  if (seconds < 0) return 'in ' + spell(-seconds);            // the phone is ahead of the server
  if (seconds >= DAY && seconds < 2 * DAY) return 'yesterday';
  return spell(seconds) + ' ago';
}

// The clock is an argument. A function that reads the real one can never be tested.
const NOW = new Date(2026, 0, 15, 12, 0, 0);
const secondsBefore = (s) => new Date(NOW.getTime() - s * 1000);
for (const s of [5, 60, 3 * HOUR, 25 * HOUR, 3 * DAY, 40 * DAY]) {
  console.log(String(s).padStart(7), 'seconds ago reads as', ago(secondsBefore(s), NOW));
}

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a few seconds is not worth a number', ago(secondsBefore(5), NOW), 'just now');
test('one minute is singular', ago(secondsBefore(60), NOW), '1 minute ago');
test('two and a half minutes rounds up, and pluralises', ago(secondsBefore(150), NOW), '3 minutes ago');
test('hours once the minutes reach sixty', ago(secondsBefore(3 * HOUR), NOW), '3 hours ago');
test('a day and a bit is yesterday', ago(secondsBefore(25 * HOUR), NOW), 'yesterday');
test('but two days is counted again', ago(secondsBefore(3 * DAY), NOW), '3 days ago');
test('thirty days rounds up into months rather than saying 30 days', [ago(secondsBefore(29 * DAY), NOW), ago(secondsBefore(40 * DAY), NOW)], ['29 days ago', '1 month ago']);
test('past a year it says years', ago(secondsBefore(400 * DAY), NOW), '1 year ago');
test('and a timestamp from the future reads forwards, not as a negative', ago(new Date(NOW.getTime() + 5 * MINUTE * 1000), NOW), 'in 5 minutes');

The design decision that makes this testable is the second parameter. Every version of this function that calls Date.now() inside can only be checked by eye, and the one case you most want to check — a timestamp slightly in the future — is impossible to stage. Pass the clock in; the caller supplies new Date() at the edge.

Future timestamps are not hypothetical. Browser clocks drift, phones are set by hand, and a record created with the client's time and rendered against the server's time routinely arrives a few seconds ahead. Without the negative branch a fresh comment reads -3 seconds ago or, worse, 1 year ago once the arithmetic goes through Math.abs somewhere careless. Absorbing anything under 45 seconds into "just now" hides most skew for free.

Two things are deliberately imprecise. Math.round, not floor, so 59 minutes reads as an hour rather than "59 minutes"; and a month is 30 days, because nobody reading a feed is counting. Precision here is not accuracy — the label is a rough anchor, and the exact timestamp belongs in a tooltip.

Common mistakes

  • Calling new Date() inside the function. The result changes every second, so it can't be tested. Pass the current time in.
  • Always adding an "s". "1 minutes ago" looks careless. Only 1 is singular.
  • Ignoring negative gaps. A slightly fast clock gives "-3 seconds ago" or worse. Handle the future on purpose.

Try it yourself

  1. Add weeks: show "2 weeks ago" for gaps from 7 to 29 days.
  2. Make the future case say "tomorrow" for a gap of one to two days ahead.
  3. Write shortAgo that returns compact labels like 5m, 3h and 2d.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.