Skip to content

Instantly share code, notes, and snippets.

@dhruvnnd
Created October 1, 2025 17:38
Show Gist options
  • Select an option

  • Save dhruvnnd/16cc10943e4cd0041f43adc754830269 to your computer and use it in GitHub Desktop.

Select an option

Save dhruvnnd/16cc10943e4cd0041f43adc754830269 to your computer and use it in GitHub Desktop.
// in milliseconds
var units = {
year: 24 * 60 * 60 * 1000 * 365,
month: 24 * 60 * 60 * 1000 * 365 / 12,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000
}
const rtf = new Intl.RelativeTimeFormat('en-GB', {
numeric: 'always',
});
/**
* Returns a human-readable relative time string between two dates.
*
* @param {Date|number} d1 - The target date or timestamp to compare.
* @param {Date|number} [d2=new Date()] - The reference date or timestamp (defaults to now).
* @returns {string} A formatted relative time string (e.g., "3 days ago", "in 2 hours").
*/
export const getRelativeTime = (d1, d2 = new Date()) => {
var elapsed = d1 - d2;
for (var unit in units) {
if (Math.abs(elapsed) > units[unit] || unit == "second") {
return rtf.format(Math.round(elapsed / units[unit]), unit)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment