首页 > 解决方案 > 带有年、月、日、小时和分钟的 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})

标签: javascriptdatecountdowndate-fns

解决方案


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

推荐阅读