Format a timestamp as relative time
Every feed, comment thread and notification list shows relative times. Passing now in explicitly rather than reading the clock inside is what makes the function testable — and it is why this version is deterministic.
Implement formatRelativeTime(timestamp, now), both epoch milliseconds. Let seconds = Math.round((now - timestamp) / 1000) — positive means the past — and abs = Math.abs(seconds).
If abs is under 60, return exactly "just now". Otherwise pick the first unit whose limit abs falls under, and take Math.floor(abs / size) as the value: minute (size 60, limit 3600), hour (3600, 86400), day (86400, 604800), week (604800, 2592000), month (2592000, 31536000), and otherwise year (size 31536000).
Build the label as the value, a space, the unit name, plus an s unless the value is exactly 1. Return "<label> ago" when seconds is positive and "in <label>" when it is negative.
What it has to do
- Return
"just now"when the difference is under 60 seconds in either direction. - Use the largest unit that fits, flooring the value, across minute, hour, day, week, month and year.
- Pluralise the unit with a trailing
sunless the value is exactly 1. - Suffix past times with
" ago"and prefix future times with"in ". - Take
nowas an argument rather than reading the clock.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.