Untitled

mail@pastecode.io avatar
unknown
typescript
a month ago
1.1 kB
3
Indexable
Never
  // countdown time left 
  type TTimeLeft = {
    days: number;
    hours: number;
    minutes: number;
    seconds: number;
  };
  const [timeLeft, setTimeLeft] = useState<TTimeLeft>({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
  });
  const calculateTimeLeftHandler = (): TTimeLeft => {
    const difference =
      new Date('2024-02-20T00:00:00').getTime() - new Date().getTime();
    let timeLeft: TTimeLeft = {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
    };
    if (difference > 0) {
      timeLeft = {
        days: Math.floor(difference / (1000 * 60 * 60 * 24)),
        hours: Math.floor(
          (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
        ),
        minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
        seconds: Math.floor((difference % (1000 * 60)) / 1000),
      };
    }
    return timeLeft;
  };
  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft(calculateTimeLeftHandler());
    }, 1000);
    return () => clearInterval(timer);
  }, []);
Leave a Comment