16. Relative Time for Notifications

EasyJavaScriptAccounts & Community

The notifications dropdown shows "just now", "5 minutes ago" or "yesterday" instead of raw dates, because people scan relative times faster. Older items show a short date.

Phones sometimes have clocks a few seconds ahead, so a notification can appear to come from the future. It must still read "just now", never "in 3 seconds".

Your task: Write formatRelativeTime(timestamp, now). Both are epoch milliseconds (UTC). Return the label.

Rules (diff = now - timestamp, always rounding down to whole units): - diff under 45 seconds, including negative diffs: "just now" - under 60 minutes: "1 minute ago" or "N minutes ago". 45 to 59 seconds counts as "1 minute ago". - under 24 hours: "1 hour ago" or "N hours ago" - under 48 hours: "yesterday" - under 7 days: "N days ago" - otherwise: "DD Mon YYYY" in UTC, for example "03 Mar 2026". Months are Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec, and the day has two digits.

Examples

Example 1

Input
  • timestamp = 1796126100000
  • now = 1796126400000
Output
  • "5 minutes ago"
Explanation
300000 ms is 5 minutes.

Example 2

Input
  • timestamp = 1772526600000
  • now = 1796126400000
Output
  • "03 Mar 2026"
Explanation
More than a week ago, so the date is shown.

Solution

Write formatRelativeTime. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.

Test Results

Click "Run Code" to test your solution.