|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | + |
| 3 | +interface CountdownTimerProps { |
| 4 | + targetDate: Date |
| 5 | + className?: string |
| 6 | +} |
| 7 | + |
| 8 | +interface TimeLeft { |
| 9 | + days: number |
| 10 | + hours: number |
| 11 | + minutes: number |
| 12 | + seconds: number |
| 13 | +} |
| 14 | + |
| 15 | +export function CountdownTimer({ targetDate, className = '' }: CountdownTimerProps) { |
| 16 | + const [timeLeft, setTimeLeft] = useState<TimeLeft>({ days: 0, hours: 0, minutes: 0, seconds: 0 }) |
| 17 | + const [isExpired, setIsExpired] = useState(false) |
| 18 | + |
| 19 | + useEffect(() => { |
| 20 | + const calculateTimeRemaining = () => { |
| 21 | + const now = new Date() |
| 22 | + const difference = targetDate.getTime() - now.getTime() |
| 23 | + |
| 24 | + if (difference <= 0) { |
| 25 | + setIsExpired(true) |
| 26 | + setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 }) |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + const days = Math.floor(difference / (1000 * 60 * 60 * 24)) |
| 31 | + const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) |
| 32 | + const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)) |
| 33 | + const seconds = Math.floor((difference % (1000 * 60)) / 1000) |
| 34 | + |
| 35 | + setTimeLeft({ days, hours, minutes, seconds }) |
| 36 | + } |
| 37 | + |
| 38 | + // Calculate immediately |
| 39 | + calculateTimeRemaining() |
| 40 | + |
| 41 | + // Set up interval to update every second |
| 42 | + const timer = setInterval(calculateTimeRemaining, 1000) |
| 43 | + |
| 44 | + return () => clearInterval(timer) |
| 45 | + }, [targetDate]) |
| 46 | + |
| 47 | + if (isExpired) { |
| 48 | + return ( |
| 49 | + <span className={className}> |
| 50 | + Registrace ukončena! |
| 51 | + </span> |
| 52 | + ) |
| 53 | + } |
| 54 | + |
| 55 | + const formatTimeUnit = (value: number, singular: string, few: string, many: string) => { |
| 56 | + if (value === 1) return singular |
| 57 | + if (value >= 2 && value <= 4) return few |
| 58 | + return many |
| 59 | + } |
| 60 | + |
| 61 | + return ( |
| 62 | + <span className={className}> |
| 63 | + {timeLeft.days > 0 && ( |
| 64 | + <> |
| 65 | + {timeLeft.days} {formatTimeUnit(timeLeft.days, 'den', 'dny', 'dní')}{' '} |
| 66 | + </> |
| 67 | + )} |
| 68 | + {timeLeft.hours > 0 && ( |
| 69 | + <> |
| 70 | + {timeLeft.hours} {formatTimeUnit(timeLeft.hours, 'hodina', 'hodiny', 'hodin')}{' '} |
| 71 | + </> |
| 72 | + )} |
| 73 | + {timeLeft.minutes > 0 && ( |
| 74 | + <> |
| 75 | + {timeLeft.minutes} {formatTimeUnit(timeLeft.minutes, 'minuta', 'minuty', 'minut')}{' '} |
| 76 | + </> |
| 77 | + )} |
| 78 | + {timeLeft.seconds} {formatTimeUnit(timeLeft.seconds, 'sekunda', 'sekundy', 'sekund')} |
| 79 | + </span> |
| 80 | + ) |
| 81 | +} |
0 commit comments