Created
April 21, 2021 00:15
-
-
Save giventofly/9c02c2648f9102b470c25d8fcb6747f5 to your computer and use it in GitHub Desktop.
javascript time ago
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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