diff --git a/components/ui/Comments.tsx b/components/ui/Comments.tsx index 16fbbb5..89de3a6 100644 --- a/components/ui/Comments.tsx +++ b/components/ui/Comments.tsx @@ -7,8 +7,8 @@ import clsx from 'clsx' import {addComment, loginWithGitHub} from '@/app/actions/comments' import {Button} from '@/components/ui/Button' import {GitHubIcon} from '@/components/icons/SocialIcons' -import {formatDistanceToNow} from 'date-fns' import {ArrowLeftIcon} from '@/components/icons/ArrowLeftIcon' +import {getShortDurationFromNow} from '@/lib/dateFns' type Comment = { id: number @@ -58,7 +58,7 @@ Comments.Comment = function Comment({comment, children, isReply = false}: { return ( <>
+ className={clsx('flex gap-x-4 py-5', isReply && 'ml-[62px] border-l border-zinc-100 pl-6 dark:border-zinc-700/40')}> {comment.user.name}
@@ -66,7 +66,7 @@ Comments.Comment = function Comment({comment, children, isReply = false}: {

{comment.user.name}

diff --git a/lib/dateFns.ts b/lib/dateFns.ts new file mode 100644 index 0000000..d477091 --- /dev/null +++ b/lib/dateFns.ts @@ -0,0 +1,32 @@ +import { + differenceInDays, + differenceInHours, + differenceInMinutes, + differenceInMonths, + differenceInSeconds, + differenceInWeeks, + differenceInYears +} from 'date-fns' + +export function getShortDurationFromNow(fromDateTime: string) { + const to = new Date() + + const units = [ + {fn: differenceInYears, suffix: 'y'}, + {fn: differenceInMonths, suffix: 'mo'}, + {fn: differenceInWeeks, suffix: 'w'}, + {fn: differenceInDays, suffix: 'd'}, + {fn: differenceInHours, suffix: 'h'}, + {fn: differenceInMinutes, suffix: 'm'}, + {fn: differenceInSeconds, suffix: 's'} + ] + + for (const {fn, suffix} of units) { + const diff = fn(to, fromDateTime) + if (Math.abs(diff) >= 1) { + return `${Math.abs(diff)}${suffix}` + } + } + + return '0s' +}