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

如何去除date-fns中intervalToDuration返回的时分秒计时

如何用date-fns只保留时间间隔中的月和日部分?

要去掉时分秒,只保留月和日的格式,有两种简单的实现方式:

方法一:通过formatDuration的format参数指定显示单位

直接在formatDuration的配置项里添加format数组,明确指定只展示months和days两个单位:

import { intervalToDuration, formatDuration } from 'date-fns';

let duration = intervalToDuration({
  start: new Date('2022-03-24'),
  end: new Date(),
});

const newD = formatDuration(duration, {
  delimiter: ', ',
  format: ['months', 'days'] // 限定仅显示月和日
});
console.log(newD);

方法二:先过滤duration对象中的时分秒属性

如果需要先处理原始的时间间隔对象,再进行格式化,可以直接删除duration里的hours、minutes、seconds(以及可选的milliseconds)属性:

import { intervalToDuration, formatDuration } from 'date-fns';

let duration = intervalToDuration({
  start: new Date('2022-03-24'),
  end: new Date(),
});

// 删除不需要的时分秒相关属性
delete duration.hours;
delete duration.minutes;
delete duration.seconds;
delete duration.milliseconds;

const newD = formatDuration(duration, {
  delimiter: ', ',
});
console.log(newD);

两种方法都能得到你想要的「6 months, 5 days」格式,按需选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:20:13