Course contentsShow
← JavaScript
Lesson 2222 of 2,72346. InternationalizationFree lesson

Time Units: second, minute, hour, day

Formatting relative times with common units from seconds to days.

Time Units: second, minute, hour, day

What you'll learn: How to format relative times using Intl.RelativeTimeFormat with the most common time units—second, minute, hour, and day.

Understanding Time Units

When you call the format() method on an Intl.RelativeTimeFormat instance, you provide two arguments: a numeric value and a unit string. The four most commonly used units are "second", "minute", "hour", and "day". Each unit lets you express how far in the past or future something occurred relative to now.

Think of these units as different zoom levels on a timeline. Seconds for very recent events, minutes for short-term happenings, hours for the same day, and days for spanning across dates.

Specifying Units in format()

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

console.log(rtf.format(-30, 'second'));  // "30 seconds ago"
console.log(rtf.format(5, 'minute'));    // "in 5 minutes"
console.log(rtf.format(-2, 'hour'));     // "2 hours ago"
console.log(rtf.format(3, 'day'));       // "in 3 days"

The numeric value indicates how many of that unit, and whether it's past (negative) or future (positive). The unit string must be one of the supported values—always lowercase and singular (not "seconds" or "minutes").

Choosing the Right Unit

Select the unit that best matches the magnitude of your time difference. For something that happened 90 seconds ago, you might choose "minute" with a value of -2 instead of "second" with -90 for readability. The unit you pick directly affects the human-readable output.

Key Takeaway: The four core time units—"second", "minute", "hour", and "day"—let you format relative times at different granularities, making your timestamps naturally readable for users.