Common Patterns: Calculating Time Differences
You'll learn: How to convert raw Date differences into the right units and signs for Intl.RelativeTimeFormat.
The Challenge
RelativeTimeFormat expects you to provide both a numeric value and a unit (like 'day' or 'hour'). It doesn't automatically calculate "how many days ago" something happened—you must do that math yourself. The pattern is straightforward: subtract timestamps, convert to the appropriate unit, and determine the sign.
Core Pattern
-
Get the difference in milliseconds:
Subtract the target date from the current date (Date.now() - pastDate.getTime()). -
Convert to the desired unit:
Divide by the milliseconds-per-unit constant (e.g.,1000 * 60 * 60 * 24for days). -
Apply the correct sign:
Past events are negative, future events are positive. Since we subtractedpastDatefromnow, past dates yield positive milliseconds—so negate the result forformat(). -
Round appropriately:
UseMath.round()for nearest unit,Math.floor()for "full units elapsed," orMath.ceil()depending on your needs.
Example Flow
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const now = Date.now();
const yesterday = new Date('2025-06-14T12:00:00Z');
const diffMs = now - yesterday.getTime();
const diffDays = Math.round(diffMs / (1000 * 60 * 60 * 24));
// Negate because it's in the past
console.log(rtf.format(-diffDays, 'day')); // "yesterday"
Choosing Units
Pick the largest sensible unit: if diffDays < 7, use 'day'; if < 30, use 'week'; otherwise 'month' or 'year'. This keeps output human-friendly ("2 weeks ago" vs "14 days ago").
Key Takeaway:
Calculate time differences by subtracting timestamps, converting to your chosen unit, negating for past events, and rounding—then pass the result and unit name to RelativeTimeFormat.format().