[英]Getting duration between two dates in date-fns in days:hrs:mins:secs format
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.我正在尝试使用 date-fns 库显示倒数计时器并按照以下方式执行操作,但无法在反应中找到解决方案。
Expected output: 60 days: 8 hours: 9 minutes: 5 seconds remaining预计 output:60 天:8 小时:9 分钟:剩余 5 秒
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任何建议或指向正确方法的指针,因为我没有看到这样的直接实现,我只能看到 formatDistance 方法,它只有一个单元
intervalToDuration is what you are looking for. 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 https://date-fns.org/v2.16.1/docs/intervalToDuration
In this case you need to use formatDistance.在这种情况下,您需要使用 formatDistance。
Import formatDistance from date-fns: import { formatDistance } from 'date-fns'从 date-fns 导入 formatDistance:从 'date-fns' 导入 { formatDistance }
Use the property with something like this: formatDistance(firstDate, secondDate, [options])使用类似这样的属性: formatDistance(firstDate, secondDate, [options])
As options, you can include, for example, the language "locale: es".作为选项,您可以包括例如语言“locale: es”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.