我正在尝试使用 date-fns 库显示倒数计时器并按照以下方式执行操作,但无法在反应中找到解决方案。
预期输出:60 天:8 小时:9 分钟:剩余 5 秒
const finishTime = new Date("01/01/2020");
const currentTime = new Date();
将结果添加到数组以便稍后遍历:
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));
添加手动逻辑以从秒中获取时间。显然应该有一个更好的逻辑 / 不使用我缺少的库:
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>
);
任何建议或指向正确方法的指针,因为我没有看到这样的直接实现,我只能看到 formatDistance 方法,它只有一个单元