Skip to content

Instantly share code, notes, and snippets.

@giventofly
Created April 21, 2021 00:15
Show Gist options
  • Save giventofly/9c02c2648f9102b470c25d8fcb6747f5 to your computer and use it in GitHub Desktop.
Save giventofly/9c02c2648f9102b470c25d8fcb6747f5 to your computer and use it in GitHub Desktop.
javascript time ago
const timeAgo = (unixtime)=>{
//no weeks
const periods = ["second", "minute", "hour", "day", "month", "year", "decade"];
const lengths = ["60","60","24","31","12","10"];
//js returns in ms instead of s
const now = Math.round(Date.now() / 1000);
let difference = now - unixtime;
let j=0;
for(j = 0; difference >= lengths[j] && j < lengths.length-1; j++) {
difference = difference / lengths[j];
console.log(j,difference,lengths[j],lengths.length,difference >= lengths[j]);
}
difference = Math.round(difference);
if(difference != 1) {
periods[j] += "s";
}
return difference + ' ' + periods[j] + ' ago';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment