From 2b6d21ce2baadbd852a0f708a86ab43963222640 Mon Sep 17 00:00:00 2001 From: Kittisak Phormraksa Date: Sat, 27 Apr 2024 12:14:41 +0700 Subject: [PATCH] [web] Edit tx display time --- web/src/components/Transactions.tsx | 9 ++--- web/src/utils/date.ts | 53 +++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 7 deletions(-) create mode 100644 web/src/utils/date.ts diff --git a/web/src/components/Transactions.tsx b/web/src/components/Transactions.tsx index fe2f3b3..ccc4a32 100644 --- a/web/src/components/Transactions.tsx +++ b/web/src/components/Transactions.tsx @@ -1,17 +1,12 @@ 'use client' import { FC, useEffect, useMemo, useState } from 'react' -import { format } from 'date-fns' import useIsMounted from '@/hooks/useIsMounted' import Axios from '@/libs/axios' import { Transaction } from '@/types' import { TransactionType } from '@/enums' - -const formatDateTime = (ts: number) => { - const f = 'yyyy-MM-dd HH:mm:ss' - return format(new Date(ts), f) -} +import { shortenTime } from '@/utils/date' const TxItem = ({ amountSat, description, createdAt, type }: Transaction) => { const amountColor = type === TransactionType.PAYMENT_SENT ? 'text-gray-100' : 'text-green-500' @@ -25,7 +20,7 @@ const TxItem = ({ amountSat, description, createdAt, type }: Transaction) => { {displayDescription}
- {formatDateTime(createdAt)} + {shortenTime(new Date(createdAt))}
diff --git a/web/src/utils/date.ts b/web/src/utils/date.ts new file mode 100644 index 0000000..bf502ac --- /dev/null +++ b/web/src/utils/date.ts @@ -0,0 +1,53 @@ +const Minute = 60 +const Hour = 3600 +const Day = 86400 +const Month = 30 * 86400 +const Year = 365 * 86400 + +export const shortenTime = (d: Date) => { + const now = new Date() + + let duration = (now.getTime() - d.getTime()) / 1000 + + if (duration < Minute) { + return 'a few seconds ago' + } + + if (duration < Hour) { + duration = Number.parseInt(String(duration / Minute)) + if (duration === 1) { + return 'a minute ago' + } + return duration + ' minutes ago' + } + + if (duration < Day) { + duration = Number.parseInt(String(duration / Hour)) + if (duration === 1) { + return 'an hour ago' + } + return duration + ' hours ago' + } + + if (duration < Month) { + duration = Number.parseInt(String(duration / Day)) + if (duration === 1) { + return 'a day ago' + } + return duration + ' days ago' + } + + if (duration < Year) { + duration = Number.parseInt(String(duration / Month)) + if (duration === 1) { + return 'a month ago' + } + return duration + ' months ago' + } + + duration = Number.parseInt(String(duration / Year)) + if (duration === 1) { + return 'a year ago' + } + return duration + ' years ago' +}