5

我正在尝试使用 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 方法,它只有一个单元

4

1 回答 1

8

intervalToDuration 是您正在寻找的。

// Get the duration between January 15, 1929 and April 4, 1968.
intervalToDuration({
  start: new Date(1929, 0, 15, 12, 0, 0),
   end: new Date(1968, 3, 4, 19, 5, 0)
})
// => { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }

https://date-fns.org/v2.16.1/docs/intervalToDuration

于 2021-03-22T13:06:58.937 回答