Skip to content

Instantly share code, notes, and snippets.

@abduljeleelng
Created May 25, 2020 23:42
Show Gist options
  • Save abduljeleelng/60e38cd761ff7fcb5e218ba6a3d4b191 to your computer and use it in GitHub Desktop.
Save abduljeleelng/60e38cd761ff7fcb5e218ba6a3d4b191 to your computer and use it in GitHub Desktop.
Format time to a go
const timeAgo = (dateTime) => {
const diff = Number(new Date()) - dateTime;
const minute = 60 * 1000;
const hour = minute * 60;
const day = hour * 24;
const month = day * 30;
const year = day * 365;
switch (true) {
case diff < minute:
const seconds = Math.round(diff / 1000);
return `${seconds} ${seconds > 1 ? 'seconds' : 'second'} ago`
case diff < hour:
return Math.round(diff / minute) + ' minutes ago';
case diff < day:
return Math.round(diff / hour) + ' hours ago';
case diff < month:
return Math.round(diff / day) + ' days ago';
case diff < year:
return Math.round(diff / month) + ' months ago';
case diff > year:
return Math.round(diff / year) + ' years ago';
default:
return "";
}
};
console.log(timeAgo(new Date(2020-05-22T15:16:20.571Z).getTime()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment