From bc90d906437f11fb387ae2444dff123db607fc1e Mon Sep 17 00:00:00 2001 From: Niloofar Date: Tue, 21 Nov 2023 11:51:47 +0800 Subject: [PATCH] feat: footer's server time --- src/components/layout/footer/ServerTime.tsx | 12 +++++---- src/constants/moment.ts | 4 +++ src/hooks/useServerTime.ts | 27 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 src/constants/moment.ts create mode 100644 src/hooks/useServerTime.ts diff --git a/src/components/layout/footer/ServerTime.tsx b/src/components/layout/footer/ServerTime.tsx index 5f6472d700..ea876fdc79 100644 --- a/src/components/layout/footer/ServerTime.tsx +++ b/src/components/layout/footer/ServerTime.tsx @@ -1,13 +1,15 @@ -import { useTranslation } from 'react-i18next'; import Tooltip from 'Components/common/tooltip'; +import useServerTime from 'Hooks/useServerTime'; +import { epochToGMTFormat, epochToLocalFormat } from 'Constants/moment'; -// TODO complete the functionality + add tests const ServerTime = () => { - const { t } = useTranslation(); + const time = useServerTime(); + const GMTFormat = epochToGMTFormat(time); + const localFormat = epochToLocalFormat(time); return ( - - 2023-11-03 03:31:07 GMT + + {GMTFormat} ); }; diff --git a/src/constants/moment.ts b/src/constants/moment.ts new file mode 100644 index 0000000000..0fbee43f99 --- /dev/null +++ b/src/constants/moment.ts @@ -0,0 +1,4 @@ +import moment from 'moment'; + +export const epochToGMTFormat = (time: number) => moment.unix(time).utc().format('YYYY-MM-DD HH:mm:ss [GMT]'); +export const epochToLocalFormat = (time: number) => moment.unix(time).utc().local().format('YYYY-MM-DD HH:mm:ss Z'); diff --git a/src/hooks/useServerTime.ts b/src/hooks/useServerTime.ts new file mode 100644 index 0000000000..69d91f5994 --- /dev/null +++ b/src/hooks/useServerTime.ts @@ -0,0 +1,27 @@ +import { useEffect, useState } from 'react'; +import useQuery from 'Api/hooks/useQuery'; + +const useServerTime = () => { + const currentDate = Date.now() / 1000; + const [serverTime, setServerTime] = useState(currentDate); + const { data } = useQuery('time', { options: { refetchInterval: 30000, refetchOnWindowFocus: false } }); + + useEffect(() => { + let timeInterval: ReturnType; + + if (data) { + setServerTime(data.time ?? currentDate); + + timeInterval = setInterval(() => { + setServerTime(prev => prev + 1); + }, 1000); + } + + return () => clearInterval(timeInterval); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [data]); + + return serverTime; +}; + +export default useServerTime;