Overview
The Relative Time plugin extends Atemporal with methods to format dates as human-readable relative time strings. It leverages nativeIntl.RelativeTimeFormat APIs for robust localization and includes intelligent caching for optimal performance.
Installation
Load the plugin using eitherextend or lazyLoad:
Methods
.fromNow(withoutSuffix?)
Calculates the relative time from the instance to now.
Signature:
withoutSuffix(optional): Iftrue, removes the “ago” or “in” prefix/suffix. Default:false
.toNow(withoutSuffix?)
Calculates the relative time from now to the instance. This is the inverse of fromNow().
Signature:
withoutSuffix(optional): Iftrue, removes the “ago” or “in” prefix/suffix. Default:false
Time Unit Selection
The plugin intelligently selects the appropriate time unit based on the difference magnitude:- Seconds: Less than 45 seconds
- Minutes: 45 seconds to 45 minutes
- Hours: 45 minutes to 22 hours
- Days: 22 hours to 26 days
- Months: 26 days to 11 months
- Years: 11 months or more
Localization
The plugin uses the default locale set on theatemporal factory and fully supports Intl.RelativeTimeFormat localization:
Performance
The plugin includes an LRU cache (max 150 entries) that stores formatted results for improved performance on repeated calls with the same parameters.Cache Management
Error Handling
The plugin includes comprehensive error handling:- Invalid dates return
"Invalid Date" - Fallback formatting is used if
IntlAPIs fail - All errors are logged to console with
console.warn()