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