Convert a date to a human-readable relative time format such as '2 hours ago' or 'in 3 days'.
Code
Generalconst rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const diff = new Date(dateStr) - new Date();
const days = Math.round(diff / (1000 * 60 * 60 * 24));
const hours = Math.round(diff / (1000 * 60 * 60));
const minutes = Math.round(diff / (1000 * 60));
return Math.abs(days) >= 1 ? rtf.format(days, 'day') : Math.abs(hours) >= 1 ? rtf.format(hours, 'hour') : rtf.format(minutes, 'minute');Parameters
ISO date string
Browser·fetch() may be limited by CORS
More JavaScript Snippets
Add Days to Date
Add a specified number of days to a date and return the result in ISO format.
Business Days Between
Calculate the number of business days (weekdays) between two dates. Excludes Saturdays and Sundays, useful for project planning and SLA calculations.
Calculate Age
Calculate age in years from a birth date, accounting for month and day.
Count Working Days
Count working days (excluding weekends) between dates.
Days Between Dates
Calculate the number of days between two dates.
Days in Month
Get the number of days in a specific month.