import { useRef, useState } from "react"; import { useInterval, UseCountdownOptions } from "hooks"; export function getTimeRemaining(endtime: string | number) { const now = new Date(); const end = new Date(endtime); let total = 0; if (now < end) { total = Date.parse(new Date(endtime) as unknown as string) - Date.parse(new Date() as unknown as string); } if (now > end) { total = Date.parse(new Date() as unknown as string) - Date.parse(new Date(endtime) as unknown as string); } const sign = now < end ? 1 : -1; const seconds = sign * Math.floor((total / 1000) % 60); const minutes = sign * Math.floor((total / 1000 / 60) % 60); const hours = sign * Math.floor((total / (1000 * 60 * 60)) % 24); const days = sign * Math.floor(total / (1000 * 60 * 60 * 24)); return { total: sign * total, days, hours, minutes, seconds, }; } const initialState = { total: 0, days: 0, hours: 0, minutes: 0, seconds: 0, }; /** * * @kind 07-Misc */ export const useCountdown = (endTime: Date | string | number, options?: UseCountdownOptions) => { const { countInPast = false } = options || {}; const time = useRef(endTime instanceof Date ? endTime.toISOString() : endTime).current; const ended = new Date(time) < new Date(); const [countdown, setCountdown] = useState(!ended || countInPast ? getTimeRemaining(time) : initialState); useInterval( () => { setCountdown(getTimeRemaining(time)); }, 1000, { disabled: ended && !countInPast }, ); return countdown; };