javascript - 带有年、月、日、小时和分钟的 date-fns 倒计时
问题描述
我正在使用DateFNS,我需要用它生成倒计时。distanceInWordsToNow
仅在大约 3 年内输出,但我需要确切的时间,例如3 Years, 11 Months, 20 Days, 3 Hours, 2 Minutes
. 如何使用 DateFNS 存档?
这是一个 CodePen 示例: https ://codepen.io/anon/pen/qGajJB
脚本
todaysDateMin: dateFns.distanceInWordsToNow(new Date(2022, 6, 2, 0, 0, 15), {addSuffix: true})
解决方案
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
你甚至可以过滤它。
// 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
推荐阅读
- java - 对于 nextInt(),Java.util.scanner 没有此类元素异常
- python - 将第二个数据源条目与主要源匹配
- python - 如何在同一个django模型的另一个值中使用一个模型的值
- python-3.x - rasterio open 和 skimage.io.read 都为我试图打开的 TIFF 返回一个 NaN 数组
- c++ - 相机抖动未激活虚幻 C++
- python - 如何在 PDF 中查找图形标题?
- html - 如何处理带有可滚动正文的固定标题
- python - 如何将 pandas.core.series.Series 绘制为条形图?
- dialogflow-es - dialogflow webhook 中的电报用户电话号码或 ID
- rest - 如何在没有用户干预的情况下在 Web 应用程序后台获取 Google 访问令牌