You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用date-fns的intlFormatDistance实现24小时内时长显示为‘今天’/‘昨天’而非‘x hours ago’

使用date-fns的intlFormatDistance实现24小时内时长显示为‘今天’/‘昨天’而非‘x hours ago’

嘿,这个需求我之前刚好碰到过,其实不用太复杂,咱们可以通过「先判断日期范围,再分情况返回文本」的方式来实现,下面给你一步步拆解:

首先,date-fns本身提供了isToday和isYesterday这两个超实用的工具方法,能帮我们快速判断目标日期是否属于自然日的今天或昨天,完全不用自己手动算时间差,省心又准确。

具体实现代码

先把需要的方法引入:

import { intlFormatDistance, isToday, isYesterday } from 'date-fns';

然后封装一个自定义的格式化函数,逻辑特别清晰:

function formatCustomTimeDistance(targetDate) {
  const currentDate = new Date();
  
  // 先判断是否是今天的日期
  if (isToday(targetDate)) {
    return 'Today';
  }
  // 再判断是否是昨天的日期
  if (isYesterday(targetDate)) {
    return 'Yesterday';
  }
  // 超出今天、昨天范围的,就用默认的intlFormatDistance生成常规提示
  return intlFormatDistance(targetDate, currentDate);
}

测试一下效果

咱们来验证几种常见场景:

// 测试今天的任意时间
const todayExample = new Date();
console.log(formatCustomTimeDistance(todayExample)); // 输出:Today

// 测试昨天的任意时间(比如20小时前)
const yesterdayExample = new Date(Date.now() - 20 * 60 * 60 * 1000);
console.log(formatCustomTimeDistance(yesterdayExample)); // 输出:Yesterday

// 测试3天前的时间
const threeDaysAgoExample = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
console.log(formatCustomTimeDistance(threeDaysAgoExample)); // 输出:3 days ago

补充:如果需要严格按24小时区间判断

要是你的需求不是按自然日,而是严格的「过去24小时内显示Today,过去24-48小时显示Yesterday」,那可以用differenceInHours来计算小时差:

import { intlFormatDistance, differenceInHours } from 'date-fns';

function formatStrictHourDistance(targetDate) {
  const currentDate = new Date();
  const hourDifference = differenceInHours(currentDate, targetDate);
  
  if (hourDifference < 24) {
    return 'Today';
  }
  if (hourDifference < 48) {
    return 'Yesterday';
  }
  return intlFormatDistance(targetDate, currentDate);
}

不过我个人更推荐第一种自然日的判断方式,毕竟这更符合咱们日常对「今天」「昨天」的认知,用户体验会更好~

备注:内容来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 08:54:34