Skip to content

Instantly share code, notes, and snippets.

@ibelick
Created March 24, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibelick/dc48ed55305ca7f2a285058fe3c55cb1 to your computer and use it in GitHub Desktop.
Save ibelick/dc48ed55305ca7f2a285058fe3c55cb1 to your computer and use it in GitHub Desktop.
Dynamic JavaScript time counter
export const dynamicTimeLeft = (date1: Date, date2: Date) => {
const distance = date2.getTime() - date1.getTime();
const hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const addZero = (t: number) => (t > 9 ? t : `0${t}`);
return `${addZero(hours)}:${addZero(minutes)}:${addZero(seconds)}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment