简体   繁体   English

以 date-fns 格式DistanceToNow 将粒度降低到天、月、年

[英]Reduce granularity to days, months, years in date-fns formatDistanceToNow

im using date-fns library to calculate distance to an event in time.我使用date-fns库及时计算到事件的距离。 For example:例如:

formatDistanceToNow(nextEventDate, { addSuffix: true });

which will produce nice human friendly output: 'in about 1 month'.这将产生对人类友好的 output:“大约 1 个月”。 All well and good, however when a distance is less then one day the same method will produce messages such as: 'in 1 minute' or 'in 3 seconds' or 'in 2 hours'.一切都很好,但是当距离小于一天时,相同的方法将产生诸如:“1 分钟内”或“3 秒内”或“2 小时内”的消息。

How can I reduce granularity such that if time frame is less than a day, then result will be 'today'?我怎样才能减少粒度,如果时间框架少于一天,那么结果将是“今天”? I would like to keep the output rounded to years, months, weeks, days but I don't want seconds, minutes, hours.我想将 output 四舍五入为年、月、周、天,但我不想要秒、分钟、小时。

I tried different method within the library (formatDistance, formatDistanceStrict) and tried removing hours, minutes and seconds from date parameter, however with no luck.我在库中尝试了不同的方法(formatDistance、formatDistanceStrict)并尝试从日期参数中删除小时、分钟和秒,但是没有运气。

Thank you.谢谢你。

The easiest method would be to manually check for distances less than 24hrs:最简单的方法是手动检查小于 24 小时的距离:

import {formatDistanceToNow} from "date-fns"
function formatDistanceDay(date: Date): string {
    const oneDay = 1000 * 3600 * 24;
    const distance = Date.now() - date.getTime();
    if (distance < oneDay && distance > 0) {
        return "today";
    }
    return formatDistanceToNow(date, {addSuffix: true})
}

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM