time-date-countdown
Version:
stable version 2 published
109 lines (94 loc) • 3.12 kB
JavaScript
import React,{FC, useState, useEffect} from "react";
const containerClass = {
display: 'flex',
flexDirection: 'row',
width: '100%',
justifyContent: 'space-evenly',
padding: '10px',
margin: '10px',
}
const textLabelClass = {
textAlign: 'center'
}
const eachCountLetterStyle = {
textAlign: 'center',
fontSize: '48px',
fontWeight: '700',
}
const MILLISECONDSPERDAY = 86400000;
const TOTALHOURS = 24;
const MILLISECONDSINHOUR = 3600000;
const MILLISECONDS = 60000;
const SECONDS = 60;
const MILLISECONDSMULTIPLER = 1000;
const getDateDiffernce = (targetTime) => {
const currentTime = new Date();
return Math.abs(targetTime - currentTime);
}
const getDateCount = (targetDate) => {
let days = '-';
let hours = '-';
let minutes = '-';
let seconds = '-';
const differenceInTime = getDateDiffernce(targetDate);
if (differenceInTime > 0) {
days = Math.floor(differenceInTime / MILLISECONDSPERDAY);
hours = Math.floor((differenceInTime / MILLISECONDSINHOUR) % TOTALHOURS);
minutes = Math.floor((differenceInTime / MILLISECONDS) % SECONDS);
seconds = Math.floor((differenceInTime / MILLISECONDSMULTIPLER) % SECONDS);
}
return {
days,
hours,
minutes,
seconds,
};
}
const CountDownTimer = ({
targetDate = new Date(new Date().getTime() + (24 * 60 * 60 * 1000)),
containerStyles = containerClass,
containerClassv2='',
textLabelClassv2=textLabelClass,
eachCountLetterStylev2=eachCountLetterStyle,
eachContainerStyle='eachContainerStyle',
}) => {
const [countLabelTime, setLabelTime] = useState({
days: '-',
hours: '-',
minutes: '-',
seconds: '-',
});
const getTimeText = () => {
const targetTime = new Date(targetDate);
console.log('targetDate', targetTime)
const countLabel = getDateCount(targetTime);
return countLabel;
}
useEffect(() => {
const interval = setInterval(() => { setLabelTime(getTimeText())}, 1000);
return () => {
clearInterval(interval);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div style={containerStyles} className={containerClassv2}>
<div className={eachContainerStyle}>
<div style={textLabelClassv2}>Days</div>
<div style={eachCountLetterStylev2}>{countLabelTime?.days}</div>
</div>
<div className={eachContainerStyle}>
<div style={textLabelClassv2}>Hours</div>
<div style={eachCountLetterStylev2}>{countLabelTime?.hours}</div>
</div>
<div className={eachContainerStyle}>
<div style={textLabelClassv2}>Minutes</div>
<div style={eachCountLetterStylev2}>{countLabelTime?.minutes}</div>
</div>
<div className={eachContainerStyle}>
<div style={textLabelClassv2}>Seconds</div>
<div style={eachCountLetterStylev2}>{countLabelTime?.seconds}</div>
</div>
</div>);
}
export default CountDownTimer;