Skip to content

Instantly share code, notes, and snippets.

@mertenvg
Created January 29, 2019 15:55
Show Gist options
  • Save mertenvg/aef22323b4a7406e708a5d3bbd55fb70 to your computer and use it in GitHub Desktop.
Save mertenvg/aef22323b4a7406e708a5d3bbd55fb70 to your computer and use it in GitHub Desktop.
Converts a time difference between a given time and the current time to a human friendly string (a.k.a timeago, moments)
const frames = [
{ name: "year", value: (d: number) => Math.floor(d / 29030400000) },
{ name: "month", value: (d: number) => Math.floor(d / 2419200000) },
{ name: "week", value: (d: number) => Math.floor(d / 604800000) },
{ name: "day", value: (d: number) => Math.floor(d / 86400000) },
{ name: "hour", value: (d: number) => Math.floor(d / 3600000) },
{ name: "minute", value: (d: number) => Math.floor(d / 60000) },
{ name: "second", value: (d: number) => Math.floor(d / 1000) },
];
function humanTimeDiff(date: Date, frame: number = 0) {
const now = new Date();
const diff = date.getTime() - now.getTime();
const t = diff < 0 ? "ago" : "left";
if (frame >= frames.length) {
return "now";
}
const f = frames[frame];
const v = f.value(Math.abs(diff));
if (v === 0) {
return humanTimeDiff(date, frame + 1);
}
return `${Math.abs(v)} ${f.name}${Math.abs(v) !== 1 ? "s" : ""} ${t}`;
}
humanTimeDiff(new Date("Tue Jan 29 2019 16:50:10 GMT+0100")); //?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment