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

如何修改Moment.js代码,实现3天后切换格式的动态日期显示?

Got it, let's adjust your code to match that date display behavior. The key changes are fixing the date parsing (since your data-date values have spaces, the original format strings were missing them), and adding custom logic to handle the "Yesterday" label and switch to the formatted date after 3 days.

Here's the modified JavaScript code:

$('.date').each(function() {
  var $this = $(this);
  var textDate = $this.data('date');
  
  // Correctly parse the date string (format matches "01 April 2018" => DD MMMM YYYY)
  var postedDate = moment(textDate, 'DD MMMM YYYY');
  
  // Handle invalid dates gracefully
  if (!postedDate.isValid()) {
    $this.text(textDate);
    return;
  }
  
  var now = moment();
  var diffInHours = now.diff(postedDate, 'hours');
  var diffInDays = now.diff(postedDate, 'days');
  
  let displayText;
  
  if (diffInHours < 24) {
    // Less than 24 hours old: use moment's built-in relative time (seconds/minutes/hours ago)
    displayText = postedDate.fromNow();
  } else if (diffInDays === 1) {
    // Exactly one day old: show "Yesterday" instead of "a day ago"
    displayText = "Yesterday";
  } else if (diffInDays <= 3) {
    // 2 or 3 days old: show "{X} days ago"
    displayText = `${diffInDays} days ago`;
  } else {
    // Older than 3 days: switch to "MMM Do YY" format (e.g., Apr 1st 18)
    displayText = postedDate.format('MMM Do YY');
  }
  
  $this.text(displayText);
});

What changed:

  1. Fixed date parsing: The original code used format strings without spaces (DDMMMMY), which wouldn't correctly parse your data-date values like "01 April 2018". We updated it to DD MMMM YYYY to match the actual format.
  2. Added invalid date handling: If the date string can't be parsed, it falls back to showing the original text instead of breaking.
  3. Custom display logic:
    • For posts under 24 hours: Uses fromNow() to show "X seconds/minutes/hours ago".
    • For exactly 1 day old: Replaces "a day ago" with "Yesterday".
    • For 2-3 days old: Shows "2 days ago" or "3 days ago".
    • For posts older than 3 days: Switches to the MMM Do YY formatted date (e.g., "May 26th 18").

Your existing HTML is fine as-is—just make sure the moment.js and jQuery scripts are loaded before this code runs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:14:15