Skip to content

Instantly share code, notes, and snippets.

@dizys
Created February 12, 2022 23:34
Show Gist options
  • Save dizys/98657b742df7d5d0333c08fe42c6fefe to your computer and use it in GitHub Desktop.
Save dizys/98657b742df7d5d0333c08fe42c6fefe to your computer and use it in GitHub Desktop.
Describe the time difference between a timestamp and now
function getTimeDifference(timestamp) {
let now = new Date();
let difference = now.getTime() - timestamp;
let seconds = Math.floor(difference / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let days = Math.floor(hours / 24);
let time = "";
if (days > 0) {
time = days + "d ago";
} else if (hours > 0) {
time = hours + "hr ago";
} else if (minutes > 0) {
time = minutes + "min ago";
} else {
time = seconds + "sec ago";
}
return time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment