Skip to content

Commit

Permalink
feat: use custom time ago formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
velut committed Aug 21, 2024
1 parent 54d75fe commit d4eaf85
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"anchor-js": "^5.0.0",
"astro": "^4.14.3",
"astro-seo": "^0.8.4",
"date-fns": "^3.6.0",
"dompurify": "^3.1.6",
"effect": "^3.6.5",
"fflate": "^0.8.2",
Expand Down
8 changes: 0 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 23 additions & 2 deletions src/scripts/time-ago.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
import { formatDistanceStrict } from "date-fns";
import { defineComponent } from "./define-component";

export const timeAgo = defineComponent((timestamp: string) => ({
text: formatDistanceStrict(new Date(timestamp), new Date(), { addSuffix: true }),
text: formatTimeAgo(timestamp),
}));

const formatTimeAgo = (timestamp: string) => {
const units = [
["year", 365 * 24 * 60 * 60 * 1000],
["month", 30 * 24 * 60 * 60 * 1000],
["day", 24 * 60 * 60 * 1000],
["hour", 60 * 60 * 1000],
["minute", 60 * 1000],
["second", 1000],
] as const;
const diff = Date.now() - new Date(timestamp).getTime();
const elapsed = Math.abs(diff);
for (const [name, size] of units) {
const value = Math.floor(elapsed / size);
if (value > 0) {
const plural = value > 1 ? "s" : "";
const description = `${value} ${name}${plural}`;
return diff > 0 ? `${description} ago` : `in ${description}`;
}
}
return "just now";
};

0 comments on commit d4eaf85

Please sign in to comment.