Skip to content

Instantly share code, notes, and snippets.

@luisfelipe-dev
Created April 3, 2023 20:25
Show Gist options
  • Save luisfelipe-dev/1254cf10094b7d735f4746a216ba1998 to your computer and use it in GitHub Desktop.
Save luisfelipe-dev/1254cf10094b7d735f4746a216ba1998 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
export type useCountdownProps = {
targetDate: any;
countDown: any;
}
const useCountdown = (targetDate: any) => {
const countDownDate = new Date(targetDate).getTime();
const [countDown, setCountDown] = useState(
countDownDate - new Date().getTime()
);
useEffect(() => {
const interval = setInterval(() => {
setCountDown(countDownDate - new Date().getTime());
}, 1000);
return () => clearInterval(interval);
}, [countDownDate]);
return getReturnValues(countDown);
};
const getReturnValues = (countDown: any) => {
const days = Math.floor(countDown / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60));
return [days, hours, minutes];
};
export { useCountdown };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment