1 import { useState } from 'react';
3 import { differenceInMilliseconds } from 'date-fns';
5 import { DAY, HOUR, MINUTE, SECOND } from '@proton/shared/lib/constants';
7 import useInterval from './useInterval';
9 const EVERY_SECOND = SECOND;
11 export interface DateCountdown {
13 * Difference between the two dates in milliseconds.
17 * Number of days remaining.
21 * Number of hours remaining.
25 * Number of minutes remaining.
29 * Number of seconds remaining.
33 * Whether the countdown is expired.
34 * `true` if the `end` date is in the past.
39 export interface DateCountdownOptions {
43 const useDateCountdown = (
45 * The date the countdown counts down to.
50 * Number of milliseconds between updates
52 interval = EVERY_SECOND,
53 }: DateCountdownOptions = {}
55 const [now, setNow] = useState(() => new Date());
57 useInterval(() => setNow(new Date()), interval);
59 const diff = differenceInMilliseconds(expiry, now);
60 const expired = diff < 0;
61 const absoluteDiff = Math.abs(diff);
62 const days = Math.floor(absoluteDiff / DAY);
63 const hours = Math.floor((absoluteDiff % DAY) / HOUR);
64 const minutes = Math.floor((absoluteDiff % HOUR) / MINUTE);
65 const seconds = Math.floor((absoluteDiff % MINUTE) / SECOND);
67 return { expired, diff, days, hours, minutes, seconds };
70 export default useDateCountdown;