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

如何用Moment.js同时按天和小时显示相对时间?有无替代库?

Absolutely, you can absolutely achieve that with Moment.js, and there are plenty of great alternatives out there too if you're looking to move away from Moment (since it's now in maintenance mode). Let's break this down:

Using Moment.js to Show Days + Hours in Relative Time

Moment.js doesn't have this format built into fromNow() by default, but it's easy to implement either by calculating the difference manually or customizing the relative time formatting.

Option 1: Manual Calculation (Simple & Direct)

This approach calculates the days and remaining hours between the target date and now, then constructs the string yourself:

// Define your target date
const targetDate = moment('2024-05-20T10:00:00');
const now = moment();

// Calculate differences
const diffDays = now.diff(targetDate, 'days');
const diffHours = now.diff(targetDate, 'hours') % 24;

// Build the relative time string
let relativeTime = '';
if (diffDays > 0) {
  relativeTime += `${diffDays} day${diffDays !== 1 ? 's' : ''}`;
}
if (diffHours > 0) {
  relativeTime += `${relativeTime ? ', ' : ''}${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
}

// Example output: "2 days, 7 hours ago"
console.log(relativeTime);

Option 2: Customize Moment's Relative Time Locale

If you want this format to work globally with fromNow(), you can override the relative time formatting rules for days:

// Update the English locale to include hours with days
moment.updateLocale('en', {
  relativeTime: {
    d: function (number) {
      // Calculate remaining hours after full days
      const hours = Math.floor(moment.duration(number, 'days').asHours()) % 24;
      if (hours === 0) {
        return `${number} day${number !== 1 ? 's' : ''} ago`;
      }
      return `${number} day${number !== 1 ? 's' : ''}, ${hours} hour${hours !== 1 ? 's' : ''} ago`;
    },
    // Keep other relative time rules as default
    h: '%d hours ago',
    m: '%d minutes ago',
    s: 'a few seconds ago',
    // ... add other units if needed
  }
});

// Now fromNow() will return the combined format
console.log(moment('2024-05-20T10:00:00').fromNow()); // "2 days, 7 hours ago"
Alternative Frontend Date Libraries

Since Moment.js is in maintenance (no new features), here are some modern alternatives that make this just as easy:

Day.js

A lightweight (~2KB) drop-in replacement for Moment.js with almost identical API:

const targetDate = dayjs('2024-05-20T10:00:00');
const now = dayjs();

const diffDays = now.diff(targetDate, 'day');
const diffHours = now.diff(targetDate, 'hour') % 24;

let relativeTime = '';
if (diffDays > 0) {
  relativeTime += `${diffDays} day${diffDays !== 1 ? 's' : ''}`;
}
if (diffHours > 0) {
  relativeTime += `${relativeTime ? ', ' : ''}${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
}

Luxon

Built by the Moment.js team, Luxon is a modern, timezone-aware library that leverages the browser's Intl API:

const targetDate = luxon.DateTime.fromISO('2024-05-20T10:00:00');
const now = luxon.DateTime.now();

// Calculate both days and hours in one diff call
const diff = now.diff(targetDate, ['days', 'hours']);

const relativeTime = [];
if (diff.days > 0) {
  relativeTime.push(`${diff.days} day${diff.days !== 1 ? 's' : ''}`);
}
if (diff.hours > 0) {
  relativeTime.push(`${diff.hours} hour${diff.hours !== 1 ? 's' : ''} ago`);
}

console.log(relativeTime.join(', ')); // "2 days, 7 hours ago"

date-fns

A functional, modular library where you only import what you need (great for bundle size):

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

const targetDate = new Date('2024-05-20T10:00:00');
const now = new Date();

const diffDays = differenceInDays(now, targetDate);
const diffHours = differenceInHours(now, targetDate) % 24;

let relativeTime = '';
if (diffDays > 0) {
  relativeTime += `${diffDays} day${diffDays !== 1 ? 's' : ''}`;
}
if (diffHours > 0) {
  relativeTime += `${relativeTime ? ', ' : ''}${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:57:37