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

Moment.js聊天消息日期格式化函数优化需求:基于日期差值的自定义时间分界格式实现

Fixing Moment.js Chat Date Formatting Function

Let's walk through fixing this chat date formatting code—there are a few key issues breaking its functionality, and we'll implement your exact requirements correctly.

What's Wrong With the Original Code?

  • You're doing math on formatted strings: dt and dtNow are human-readable date strings (like "March 9th 2021, 7:16:16 pm"), so subtracting them gives NaN instead of a valid date difference.
  • Calling methods that don't exist: diffDate is a number, but you try to call .diff() on it—this will throw an immediate error.
  • Missing required formatting rules: The code doesn't handle displaying yesterday's messages as LL, or the special 11:59pm/12pm boundary rules.

Fixed Implementation

const formatChatDate = (chatDate) => {
  // Keep Moment date instances (don't format immediately) for calculations
  const messageMoment = Moment(chatDate);
  const nowMoment = Moment();

  // Check if message is from the current day
  const isSameDay = nowMoment.isSame(messageMoment, 'day');
  // Check if message is from yesterday
  const isYesterday = nowMoment.subtract(1, 'day').isSame(messageMoment, 'day');

  if (isSameDay) {
    const hour = messageMoment.hour();
    const minute = messageMoment.minute();
    
    // Special case: 11:59pm shows LL format
    if (hour === 23 && minute === 59) {
      return messageMoment.format("LL");
    }
    // Special case: 12pm shows LT format
    else if (hour === 12 && minute === 0) {
      return messageMoment.format("LT");
    }
    // All other same-day messages show LT format
    else {
      return messageMoment.format("LT");
    }
  }
  // Yesterday's messages show LL format
  else if (isYesterday) {
    return messageMoment.format("LL");
  }
  // Older messages fall back to LLL format (matches original code's else case)
  else {
    return messageMoment.format("LLL");
  }
};

Key Improvements

  • Uses Moment's built-in date comparison: isSame('day') handles time zones and date boundaries reliably, avoiding messy manual millisecond calculations.
  • Preserves Moment instances: We don't format dates until we need to, so we can use all of Moment's utility methods for checks and calculations.
  • Covers all required rules:
    • Same-day messages default to LT (time-only format)
    • 11:59pm same-day messages override to LL (date-only format)
    • 12pm same-day messages keep LT format
    • Yesterday's messages show LL format
    • Older messages use LLL (full date + time format)

内容的提问来源于stack exchange,提问作者user11523613

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:22:41