I'm trying to display a count-down timer using date-fns library and doing things the below way, unable to find the solution in react.
Expected output: 60 days : 8 hours : 9 minutes : 5 seconds remaining
const finishTime = new Date("01/01/2020");
const currentTime = new Date();
Adding results to array to traverse later:
results.push(differenceInMonths(finishTime, currentTime));
results.push(differenceInDays(finishTime, currentTime));
results.push(differenceInHours(finishTime, currentTime));
results.push(differenceInMinutes(finishTime, currentTime));
results.push(differenceInSeconds(finishTime, currentTime));
Adding manual logic to get the time from seconds. There should obviously be a better logic wiht / without using the library, which I'm missing:
const monthsRemaining = results[4] / (30 * 24 * 3600); // this will anyways fail as 30 days is not common for every month
const daysRemaining = (monthsRemaining % 1) * 30;
const hoursRemaining = (daysRemaining % 1) * 24;
const minutesRemaining = (hoursRemaining % 1) * 60;
const secondsRemaining = (minutesRemaining % 1) * 60;
return (
<div>
{Math.round(monthsRemaining)} Months : {Math.round(daysRemaining)}{" "}
days : {Math.round(hoursRemaining)} hours :{" "}
{Math.round(minutesRemaining)} minutes :{" "}
{Math.round(secondsRemaining)} seconds
</div>
);
Any suggestions or pointers to the right methods, as I don't see such direct implementation, I could only see formatDistance method which only one unit