Skip to content

Instantly share code, notes, and snippets.

@lahin31
Last active September 25, 2022 16:00
Show Gist options
  • Save lahin31/0b14c383140c67bcae5e51c521172ddd to your computer and use it in GitHub Desktop.
Save lahin31/0b14c383140c67bcae5e51c521172ddd to your computer and use it in GitHub Desktop.
JavaScript Utility Function to get time ago etc

For example

timeAgo('Sun Sep 25 2022 12:57:46 GMT+0600 (Bangladesh Standard Time)'); // 16 seconds ago
function timeAgo(input) {
const date = (input instanceof Date) ? input : new Date(input);
const formatter = new Intl.RelativeTimeFormat('en');
const ranges = {
years: 3600 * 24 * 365,
months: 3600 * 24 * 30,
weeks: 3600 * 24 * 7,
days: 3600 * 24,
hours: 3600,
minutes: 60,
seconds: 1
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (let key in ranges) {
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key];
return formatter.format(Math.round(delta), key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment