import { useState, useEffect } from "react"; const SECOND = 1_000; const MINUTE = SECOND * 60; const HOUR = MINUTE * 60; const DAY = HOUR * 24; export default function useTimer(deadline, interval = SECOND) { const [timespan, setTimespan] = useState(new Date(deadline) - Date.now()); useEffect(() => { const intervalId = setInterval(() => { setTimespan((_timespan) => _timespan - interval); }, interval); return () => { clearInterval(intervalId); }; }, [interval]); /* If the initial deadline value changes */ useEffect(() => { setTimespan(new Date(deadline) - Date.now()); }, [deadline]); function checkTime(i: string | number) { if (i < 10) i = "0" + i return i; } // if want 0 before number return { //days: checkTime( Math.floor(timespan / DAY)), // } return { days: Math.floor(timespan / DAY), hours: Math.floor((timespan / HOUR) % 24), minutes: Math.floor((timespan / MINUTE) % 60), seconds: Math.floor((timespan / SECOND) % 60) }; } // usage const { days, hours, minutes, seconds } = useTimer("2022-12-31T23:59:59"); (new Date(+timeStampinSeconds * 1000).toISOString()).slice(0, 19))
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter