[英]Countdown in date-fns with years, months, days, hours & minutes
I'm using DateFNS and I need to generate a countdown with it.我正在使用DateFNS ,我需要用它生成一个倒计时。
distanceInWordsToNow
only outputs in about 3 years but I need the exact time like 3 Years, 11 Months, 20 Days, 3 Hours, 2 Minutes
. distanceInWordsToNow
只输出大约 3 年,但我需要确切的时间,如3 Years, 11 Months, 20 Days, 3 Hours, 2 Minutes
。 How to archive that with DateFNS?如何使用 DateFNS 存档?
Here is a CodePen example: https://codepen.io/anon/pen/qGajJB这是一个 CodePen 示例: https ://codepen.io/anon/pen/qGajJB
SCRIPT脚本
todaysDateMin: dateFns.distanceInWordsToNow(new Date(2022, 6, 2, 0, 0, 15), {addSuffix: true})
The formatDuration()
function in date-fns v2 does exactly what you want it to. date-fns v2 中的
formatDuration()
函数完全符合您的要求。
import { formatDuration, intervalToDuration } from 'date-fns'
let duration = intervalToDuration({
start: new Date(2022, 6, 2, 0, 0, 15),
end: new Date(),
})
formatDuration(duration, {
delimiter: ', '
})
// 2 years, 15 days, 23 hours, 49 minutes, 35 seconds
You can even filter it.你甚至可以过滤它。
// take the first three nonzero units
const units = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']
const nonzero = Object.entries(duration).filter(([_, value]) => value || 0 > 0).map(([unit, _]) => unit)
formatDuration(duration, {
format: units.filter(i => new Set(nonzero).has(i)).slice(0, 3),
delimiter: ', '
})
// 2 years, 15 days, 23 hours
You can try something like this:你可以尝试这样的事情:
let humanizeFutureToNow = fDate => { let result = [], now = new Date() let parts = ['year', 'month', 'day', 'hour', 'minute'] parts.forEach((p, i) => { let uP = p.charAt(0).toUpperCase() + p.slice(1) let t = dateFns[`differenceIn${uP}s`](fDate, now); if (t) { result.push(`${i===parts.length-1 ? 'and ' : ''}${t} ${uP}${t===1 ? '' : 's'}`); if (i < parts.length) fDate = dateFns[`sub${uP}s`](fDate, t); } }) return result.join(' '); } console.log(humanizeFutureToNow(new Date('2022-11-11')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
The idea is to run through all the time periods you want (and have supported date-fns functions) and generate an array with all the strings.这个想法是遍历你想要的所有时间段(并支持 date-fns 函数)并生成一个包含所有字符串的数组。 We do this by running the supported
differenceIn<PARTGOESHERE>
first to get the time distance
and then subtract it using the sub<PARTGOESHERE>
function.为此,我们首先运行支持的
differenceIn<PARTGOESHERE>
以获取时间distance
,然后使用sub<PARTGOESHERE>
函数减去它。 After that just join them to compose the final string.之后,只需加入它们即可组成最终的字符串。
From here you can customize and export the parts as a parameter, as well as the uppercasing of the first letters in the output etc etc.从这里您可以自定义和导出部分作为参数,以及输出中第一个字母的大写等。
Here is also a lodash version:这里还有一个 lodash 版本:
let humanizeFutureToNow = fDate => { let result = [], now = new Date() let parts = ['year', 'month', 'day', 'hour', 'minute'] _.each(parts, (p, i) => { let scPart = _.startCase(p) let t = _.invoke(dateFns, `differenceIn${scPart}s`, fDate, now); if (t) { result.push(`${i===parts.length-1 ? 'and ' : ''}${t} ${scPart}${t===1 ? '' : 's'}`); if (i < parts.length) fDate = _.invoke(dateFns, `sub${scPart}s`, fDate, t); } }) return result.join(' '); } console.log(humanizeFutureToNow(new Date('2022-11-11')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
Use the following dateFns functions to get the components, then concatenate them together with the strings.使用以下 dateFns 函数获取组件,然后将它们与字符串连接在一起。
let x be the smaller year, y be the larger save differenceInYears called on x and y which gives the whole number of years in a variable pass x and that as a parameter to addYears, assign to x让 x 是较小的年份,y 是较大的保存差异在 x 和 y 上调用的差异 InYears,它给出了变量传递 x 中的整数年数,并将其作为 addYears 的参数,分配给 x
call differenceInMonths on x and y, save call addMonths on x and that saved number of months在 x 和 y 上调用 differenceInMonths,在 x 上调用 addMonths 并保存月数
do the same with differenceInDays and addDays, differenceInHours and addHours Now x is less than 60 minutes away from y, so call differenceInMinutes and you're done (assuming your countDown is down to the minute).对 differenceInDays 和 addDays、differentInHours 和 addHours 做同样的事情 现在 x 离 y 不到 60 分钟,所以调用 differenceInMinutes 就完成了(假设你的倒计时到分钟)。
Here is your example as run on runkit.com to illustrate the method.这是您在 runkit.com 上运行的示例以说明该方法。
var dateFns = require("date-fns");
var x = new Date();
var y = new Date(2022, 2, 6, 0, 0, 15);
var temp;
temp = dateFns.differenceInYears(y, x);
var result = temp + " years ";
x = dateFns.addYears(x, temp);
temp = dateFns.differenceInMonths(y, x);
result = result + temp + " months ";
x = dateFns.addMonths(x, temp);
temp = dateFns.differenceInDays(y, x);
result = result + temp + " days ";
x = dateFns.addDays(x, temp);
temp = dateFns.differenceInHours(y, x);
result = result + temp + " hours ";
x = dateFns.addHours(x, temp);
temp = dateFns.differenceInMinutes(y, x);
result = result + temp + " minutes ";
x = dateFns.addMinutes(x, temp);
temp = dateFns.differenceInSeconds(y, x);
result = result + temp + " seconds";
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.