Relative time: 3 days ago and in 2 hours in JavaScript
Intermediate · 4 min read
Chat apps, comment sections and notification lists rarely show a full date. They say "3 days ago", "just now" or "in 2 hours". People read that faster than 15/01/2026 12:00, so it is one of the most common date features on the web.
In this tutorial you will write relativeTime(then, now), which describes one date compared with another. It handles the past and the future, says "1 day" instead of "1 days", and says "just now" for anything within a few seconds. You need to know that subtracting two dates gives milliseconds, and how arrays and arrow functions work.
Subtracting dates gives milliseconds
When you subtract one date from another, JavaScript subtracts their timestamps. The answer is the gap in milliseconds:
console.log(new Date(2026, 0, 15, 12, 0, 5) - new Date(2026, 0, 15, 12, 0, 0)); // 5000
Five seconds is 5,000 milliseconds. If you subtract the other way round, you get -5000. That sign is useful: we will use it to tell the past from the future.
Picking a unit
"90,000 seconds ago" is correct, but no one wants to read it. The trick is to pick the largest unit that fits at least once. 90,000 seconds is more than a day (86,400 seconds) but less than a week, so we say "1 day ago".
Here is the exercise. Try it yourself first if you like, then read on and we will build it step by step.
43 "3 days ago" and "in 2 hours"
fairDescribe one date relative to another in words. Handle past and future, get the plural right, and say "just now" for anything within the last few seconds.
Stuck? Three hints, smallest first
- 1. Work in seconds, keep the sign to tell past from future, and use the size for the wording.
- 2. A table of unit names and their length in seconds, largest first, beats a chain of
ifs. - 3. Build the offsets in milliseconds from one fixed "now", so the test cannot be affected by the clock or the zone.
Step 1: name the lengths of time
Give each length a name, built up from one second in milliseconds:
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const now = new Date(2026, 0, 15, 12, 0, 0);
const off = (ms) => new Date(now.getTime() - ms);
console.log(off(3 * DAY).getDate()); // 12
now is a fixed moment, so the examples give the same answers whenever you run them. off(ms) makes a date that many milliseconds before now. A negative number goes forward, so off(-2 * HOUR) is two hours later.
Step 2: the gap in seconds, with its sign
const gapSeconds = (then) => Math.round((now - then) / 1000);
console.log(gapSeconds(off(3 * DAY))); // 259200
console.log(gapSeconds(off(-2 * HOUR))); // -7200
Positive means then is in the past. Negative means it is in the future. Math.abs removes the sign so we can look at the size on its own: Math.abs(-7200) is 7200.
Step 3: a table of units, largest first
Instead of a long chain of if checks, put the units in a list. Each entry is a name and its length in seconds:
const UNITS = [
['year', 31536000], ['month', 2592000], ['week', 604800],
['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1],
];
console.log(UNITS.find((unit) => 259200 >= unit[1])); // [ 'day', 86400 ]
find walks the list from the top and stops at the first entry that matches. Because the list goes from largest to smallest, the first unit that fits is the coarsest one that makes sense. A year here is 365 days and a month is 30 days. Those are rough, which is fine for "2 months ago" but not for anything like an invoice.
Step 4: count the units, and the plural trap
Math.floor rounds down, so 259,200 seconds divided by 86,400 is 3 days. A first try at the label adds an "s":
const naiveLabel = (count, name) => count + ' ' + name + 's';
console.log(naiveLabel(3, 'day')); // '3 days'
console.log(naiveLabel(1, 'day')); // '1 days'
"1 days" is the bug people notice first. Only add the "s" when the count isn't 1:
const label = (count, name) => count + ' ' + name + (count === 1 ? '' : 's');
console.log(label(1, 'day')); // '1 day'
Step 5: put it together
function relativeTime(then, now) {
const seconds = Math.round((now - then) / 1000);
const size = Math.abs(seconds);
if (size < 45) return 'just now';
const [name, length] = UNITS.find((unit) => size >= unit[1]);
const count = Math.floor(size / length);
const label = count + ' ' + name + (count === 1 ? '' : 's');
return seconds > 0 ? label + ' ago' : 'in ' + label;
}
console.log(relativeTime(off(3 * DAY), now)); // '3 days ago'
console.log(relativeTime(off(DAY), now)); // '1 day ago'
console.log(relativeTime(off(-2 * HOUR), now)); // 'in 2 hours'
console.log(relativeTime(off(30 * SECOND), now)); // 'just now'
const [name, length] = ... unpacks the two items of the matching entry into two names. This is called destructuring. Anything under 45 seconds returns "just now" before the table is used, so find always has at least 45 seconds to work with and always finds a unit.
The last line picks the wording: "3 days ago" for the past, "in 2 hours" for the future.
Step 6: rounding down on purpose
console.log(relativeTime(off(90 * MINUTE), now)); // '1 hour ago'
console.log(relativeTime(off(7 * DAY), now)); // '1 week ago'
console.log(relativeTime(off(400 * DAY), now)); // '1 year ago'
90 minutes becomes "1 hour ago", not "2 hours ago". Rounding down never claims that more time has passed than really has.
Notice that now is passed in instead of read inside the function. That keeps the function testable: the same inputs always give the same answer.
The full solution
The panel has the constants, the unit table and relativeTime. It prints past and future examples, plus one that uses a copy of now as the clock. The checks cover plurals, "just now", rounding, weeks and years. Press Run to see them.
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
// Largest first, so the first match is the coarsest sensible unit.
const UNITS = [
['year', 31536000], ['month', 2592000], ['week', 604800],
['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1],
];
function relativeTime(then, now) {
const seconds = Math.round((now - then) / 1000); // positive = in the past
const size = Math.abs(seconds);
if (size < 45) return 'just now';
const [name, length] = UNITS.find((unit) => size >= unit[1]);
const count = Math.floor(size / length);
const label = count + ' ' + name + (count === 1 ? '' : 's'); // no "1 days"
return seconds > 0 ? label + ' ago' : 'in ' + label;
}
// Offsets are built in milliseconds from one fixed instant, so this is the same
// in every time zone.
const now = new Date(2026, 0, 15, 12, 0, 0);
const off = (ms) => new Date(now.getTime() - ms);
console.log('3 days back ->', relativeTime(off(3 * DAY), now));
console.log('1 day back ->', relativeTime(off(DAY), now));
console.log('2 hours ahead ->', relativeTime(off(-2 * HOUR), now));
console.log('the live clock ->', relativeTime(off(90 * MINUTE), new Date(now.getTime())));
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.
test('three days in the past', relativeTime(off(3 * DAY), now), '3 days ago');
test('one day is singular', relativeTime(off(DAY), now), '1 day ago');
test('the future reads the other way round', relativeTime(off(-2 * HOUR), now), 'in 2 hours');
test('and is singular too where it should be', relativeTime(off(-HOUR), now), 'in 1 hour');
test('anything within 45 seconds is just now', relativeTime(off(30 * SECOND), now), 'just now');
test('90 minutes rounds down to the hour', relativeTime(off(90 * MINUTE), now), '1 hour ago');
test('seven days is reported as a week', relativeTime(off(7 * DAY), now), '1 week ago');
test('and 400 days as a year', relativeTime(off(400 * DAY), now), '1 year ago');
test('the same instant is just now', relativeTime(now, now), 'just now');
Two things make this testable. The unit table replaces a ladder of ifs, and both dates are arguments — a relativeTime(then) that reads Date.now() internally can only be checked by eye.
The rounding is deliberately coarse and deliberately downward: 90 minutes is "1 hour ago", not "2 hours ago", because saying more time has passed than really has is the worse error. Note that the month and year lengths in the table are approximations, 30 and 365 days, which is fine for a phrase like "2 months ago" and not fine for anything you would put in an invoice. When a real month boundary matters, use monthsBetween from exercise 28.
Intl.RelativeTimeFormat does this properly, with translations and each language's plural rules. Reach for it in production; write this once to understand what it is doing.
Common mistakes
- Always adding an "s". You get "1 days ago". Check whether the count is 1.
- Listing units smallest first.
findwould then stop at "second" every time, so you get "259200 seconds ago". - Reading the clock inside the function. A
relativeTime(then)that callsDate.now()itself gives a different answer every time, so it can't be tested. Passnowin.
Try it yourself
- Make anything between 1 and 2 days in the past say "yesterday".
- Change the "just now" limit to 10 seconds and see which examples change.
- Compare your output with the built-in
new Intl.RelativeTimeFormat('en').format(-3, 'day'), which gives "3 days ago" and also handles other languages.