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
73
74
75
76
77
|
import React, { useEffect, useState } from "react";
interface CountdownProps {
targetDate: string;
}
const Countdown: React.FC<CountdownProps> = ({ targetDate }) => {
const calculateTimeLeft = () => {
const difference =
new Date(targetDate).getTime() - new Date().getTime();
let timeLeft = {
days: "0",
hours: "0",
minutes: "0",
seconds: "0",
};
if (difference > 0) {
timeLeft = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)).toString(),
hours: Math.floor(
(difference / (1000 * 60 * 60)) % 24,
).toString(),
minutes: Math.floor((difference / 1000 / 60) % 60).toString(),
seconds: Math.floor((difference / 1000) % 60).toString(),
};
}
return timeLeft;
};
const [timeLeft, setTimeLeft] = useState({
days: "--",
hours: "--",
minutes: "--",
seconds: "--",
});
useEffect(() => {
setTimeLeft(calculateTimeLeft());
const timer = setInterval(() => {
setTimeLeft(calculateTimeLeft());
}, 1000);
return () => clearInterval(timer);
}, [targetDate]);
return (
<div className="bg-gray-700 text-white font-sans">
<div className="flex gap-2 text-2xl font-bold">
<div className="flex flex-col items-center">
<div className="text-2xl sm:text-4xl">{timeLeft.days}</div>
<div className="text-xs uppercase">Days</div>
</div>
<div className="flex flex-col items-center">
<div className="text-2xl sm:text-4xl">{timeLeft.hours}</div>
<div className="text-xs uppercase">Hours</div>
</div>
<div className="flex flex-col items-center">
<div className="text-2xl sm:text-4xl">
{timeLeft.minutes}
</div>
<div className="text-xs uppercase">Minutes</div>
</div>
<div className="flex flex-col items-center">
<div className="text-2xl sm:text-4xl">
{timeLeft.seconds}
</div>
<div className="text-xs uppercase">Seconds</div>
</div>
</div>
</div>
);
};
export default Countdown;
|