forked from Gatheraa/Gatherraa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventCountdownTimer.tsx
More file actions
72 lines (56 loc) · 1.62 KB
/
EventCountdownTimer.tsx
File metadata and controls
72 lines (56 loc) · 1.62 KB
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
'use client';
import React, { useState, useEffect } from 'react';
interface EventCountdownTimerProps {
startTime: Date;
}
const EventCountdownTimer: React.FC<EventCountdownTimerProps> = ({ startTime }) => {
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());
useEffect(() => {
const timer = setInterval(() => {
setTimeLeft(calculateTimeLeft());
}, 1000);
return () => clearInterval(timer);
}, [startTime]);
function calculateTimeLeft() {
const now = new Date();
const difference = startTime.getTime() - now.getTime();
if (difference <= 0) {
return {
isLive: now >= startTime,
isEnded: now > startTime,
};
}
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);
return {
days,
hours,
minutes,
seconds,
isLive: false,
isEnded: false,
};
}
if (timeLeft.isLive) {
return <span>Live</span>;
}
if (timeLeft.isEnded) {
return <span>Ended</span>;
}
if (timeLeft.days === undefined) return null;
return (
<div>
{timeLeft.days}d {timeLeft.hours}h {timeLeft.minutes}m {timeLeft.seconds}s
</div>
);
};
export default EventCountdownTimer;
/*
Example Usage:
<EventCountdownTimer startTime={new Date('2024-01-01T10:00:00')} />
Possible improvements:
Make it look nicer with some CSS
Add handling for cases where the event has already started
*/