如何修改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:
- Fixed date parsing: The original code used format strings without spaces (
DDMMMMY), which wouldn't correctly parse yourdata-datevalues like "01 April 2018". We updated it toDD MMMM YYYYto match the actual format. - Added invalid date handling: If the date string can't be parsed, it falls back to showing the original text instead of breaking.
- 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 YYformatted date (e.g., "May 26th 18").
- For posts under 24 hours: Uses
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
相关产品推荐
相关产品推荐

