Last active
February 13, 2021 20:36
-
-
Save jweyrich/f39c496b83f73d2c5b0587f4d841651b to your computer and use it in GitHub Desktop.
Dummy humanize functions in TypeScript
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
interface TimeUnit { | |
[key: string]: number; | |
} | |
const TIME_UNITS: TimeUnit = { | |
"year": 3.154e+10, | |
"month": 2.628e+9, | |
"week": 6.048e+8, | |
"day": 8.64e+7, | |
"hour": 3.6e+6, | |
"minute": 60000, | |
"second": 1000, | |
}; | |
export function humanizeAbsolute(when: Date | number) { | |
const diff = new Date().getTime() - (typeof when === 'number' ? when : when.getTime()); | |
for (const unit in TIME_UNITS) { | |
const quotient = Math.floor(diff / TIME_UNITS[unit]); | |
if (quotient > 0) { | |
return `${quotient} ${unit}${quotient > 1 ? "s" : ""} ago`; | |
} | |
} | |
return "just now"; | |
} | |
export function humanizeRelative(pastMilliseconds: number) { | |
return humanizeAbsolute(new Date().getTime() - pastMilliseconds); | |
} | |
// console.log(humanizeAbsolute(new Date("2021-02-13T19:42:00Z"))); | |
// console.log(humanizeAbsolute(new Date("2021-02-13T19:42:00Z").getTime())); | |
// console.log(humanizeRelative(360000)); // 1 hour | |
// console.log(humanizeRelative(2000)); // 2 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment