File size: 1,620 Bytes
6d65f0c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import { useState, useEffect } from 'react';
interface CountdownData {
days: number;
hours: number;
minutes: number;
seconds: number;
isExpired: boolean;
}
export const useCountdown = (targetDate: Date | null): CountdownData => {
const [countdown, setCountdown] = useState<CountdownData>({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
isExpired: false,
});
useEffect(() => {
if (!targetDate) {
setCountdown({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
isExpired: true,
});
return;
}
const updateCountdown = () => {
const now = new Date().getTime();
const target = targetDate.getTime();
const difference = target - now;
if (difference <= 0) {
setCountdown({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
isExpired: true,
});
return;
}
const days = Math.floor(difference / (1000 * 60 * 60 * 24));
const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((difference % (1000 * 60)) / 1000);
setCountdown({
days,
hours,
minutes,
seconds,
isExpired: false,
});
};
// Update immediately
updateCountdown();
// Set up interval to update every second
const interval = setInterval(updateCountdown, 1000);
return () => clearInterval(interval);
}, [targetDate]);
return countdown;
}; |