Skip to content

Instantly share code, notes, and snippets.

@jweyrich
Last active February 13, 2021 20:36
Show Gist options
  • Save jweyrich/f39c496b83f73d2c5b0587f4d841651b to your computer and use it in GitHub Desktop.
Save jweyrich/f39c496b83f73d2c5b0587f4d841651b to your computer and use it in GitHub Desktop.
Dummy humanize functions in TypeScript
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