Please write a JavaScript function that formats the relative distance between two date…
- User
Please write a JavaScript function that formats the relative distance between two date objects using Intl.RelativeTimeFormat and appropriate selection of either seconds, minutes, hours, days, weeks, months or years.
- Assistant
Below is a JavaScript function that calculates and formats the relative distance between two
Dateobjects usingIntl.RelativeTimeFormat. The function automatically selects the most appropriate unit (seconds, minutes, hours, days, weeks, months, or years) based on the difference between the two dates.function formatRelativeTime(date1, date2 = new Date()) { const units = [ { name: 'year', limit: 31536000000, inSeconds: 31536000 }, // 60 * 60 * 24 * 365 { name: 'month', limit: 2592000000, inSeconds: 2592000 }, // 60 * 60 * 24 * 30 { name: 'week', limit: 604800000, inSeconds: 604800 }, // 60 * 60 * 24 * 7 { name: 'day', limit: 86400000, inSeconds: 86400 }, // 60 * 60 * 24 { name: 'hour', limit: 3600000, inSeconds: 3600 }, // 60 * 60 { name: 'minute', limit: 60000, inSeconds: 60 }, { name: 'second', limit: 1000, inSeconds: 1 } ]; const diff = Math.abs(date1 - date2); const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }); for (const unit of units) { if (diff >= unit.limit) { const value = Math.round(diff / unit.limit); return formatter.format(Math.sign(date1 - date2) * value, unit.name); } } return formatter.format(0, 'second'); // Default to "now" if the difference is very small } // Example usage: const date1 = new Date('2023-10-01T12:00:00Z'); const date2 = new Date('2023-10-15T12:00:00Z'); console.log(formatRelativeTime(date1, date2)); // Output: "2 weeks ago" or "in 2 weeks"Explanation:
- Units Array: Defines time units (year, month, week, etc.) along with their limits in milliseconds and seconds.
- Difference Calculation: Computes the absolute difference between the two dates in milliseconds.
- Loop Through Units: Iterates through the units array to find the most appropriate unit based on the difference.
- Intl.RelativeTimeFormat: Formats the relative time using the selected unit and value.
- Sign Handling: Uses
Math.sign(date1 - date2)to determine if the result should be "ago" or "in".
This function works for both past and future dates relative to the reference date (
date2, defaulting tonew Date()if not provided).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.