Skip to content

Instantly share code, notes, and snippets.

@Muzammil-cyber
Created April 28, 2024 10:15
Show Gist options
  • Save Muzammil-cyber/599efe51f7ee669466fc4591d2d285bd to your computer and use it in GitHub Desktop.
Save Muzammil-cyber/599efe51f7ee669466fc4591d2d285bd to your computer and use it in GitHub Desktop.
const dateCreated = () => {
// How long since created?
const msPerMinute = 60 * 1000;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
const msPerMonth = msPerDay * 30;
const msPerYear = msPerDay * 365;
const current = new Date();
const created = new Date(post.createdAt);
const elapsed = current.getTime() - created.getTime();
if (elapsed < msPerMinute) {
return Math.round(elapsed / 1000) + " seconds ago";
} else if (elapsed < msPerHour) {
return Math.round(elapsed / msPerMinute) + " minutes ago";
} else if (elapsed < msPerDay) {
return Math.round(elapsed / msPerHour) + " hours ago";
} else if (elapsed < msPerMonth) {
return Math.round(elapsed / msPerDay) + " days ago";
} else if (elapsed < msPerYear) {
return Math.round(elapsed / msPerMonth) + " months ago";
} else {
return Math.round(elapsed / msPerYear) + " years ago";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment