1import { useState, useEffect } from "react";
2
3export function useCountdown(targetDate: Date) {
4 const countDownDate = new Date(targetDate).getTime();
5
6 const [countDown, setCountDown] = useState(
7 countDownDate - new Date().getTime()
8 );
9
10 useEffect(() => {
11 const interval = setInterval(() => {
12 setCountDown(countDownDate - new Date().getTime());
13 }, 1000);
14
15 return () => clearInterval(interval);
16 }, [countDownDate]);
17
18 return getReturnValues(countDown);
19}
20
21const getReturnValues = (countDown: number) => {
22 const days = Math.floor(countDown / (1000 * 60 * 60 * 24));
23 const hours = Math.floor(
24 (countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
25 );
26 const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60));
27 const seconds = Math.floor((countDown % (1000 * 60)) / 1000);
28
29 return [days, hours, minutes, seconds];
30};