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

Angular项目使用Dayjs计算时间差如何解决格式及单复数问题

解决方案

不要解析from方法返回的字符串,直接通过计算时间差匹配最优单位即可,完全避免自定义字符串处理逻辑,可按以下两种方案实现:

方案一:无额外依赖(推荐)

不需要引入额外Dayjs插件,逻辑可控,适配所有场景:

import dayjs from 'dayjs';
import isNil from 'lodash/isNil';

// 按量级从大到小定义时间单位配置
const TIME_UNITS = [
  { ms: 365 * 24 * 60 * 60 * 1000, label: 'year' },
  { ms: 30 * 24 * 60 * 60 * 1000, label: 'month' },
  { ms: 24 * 60 * 60 * 1000, label: 'day' },
  { ms: 60 * 60 * 1000, label: 'hour' },
  { ms: 60 * 1000, label: 'minute' },
  { ms: 1000, label: 'second' },
] as const;

calculateDelay(alertDate: string, operationDate: string): string | undefined {
  if (isNil(alertDate) || isNil(operationDate)) return undefined;

  // 计算两个日期的绝对毫秒差
  const diffMs = Math.abs(dayjs(alertDate).diff(dayjs(operationDate), 'millisecond'));

  // 匹配最优单位
  for (const { ms, label } of TIME_UNITS) {
    const count = Math.floor(diffMs / ms);
    if (count >= 1) {
      return `${count} ${label}${count > 1 ? 's' : ''}`;
    }
  }

  // 小于1秒的场景自定义返回值
  return '1 second';
}

该方案优势:

  • 完全规避from返回值中one、some等特殊字符串的处理问题
  • 单复数逻辑自主可控,不会出现1 seconds类语法错误
  • 单位适配逻辑和原生from方法完全一致,优先取最大符合量级的单位
  • 无额外依赖,性能优于字符串解析方案

方案二:使用Dayjs官方插件(差值计算更精准)

如果可以接受引入额外插件,可使用Dayjs官方的duration和humanize插件,自动处理单位适配和单复数:

  1. 先安装依赖:
npm install @dayjs/plugin-duration @dayjs/plugin-humanize
  1. 代码实现:
import dayjs from 'dayjs';
import duration from '@dayjs/plugin-duration';
import humanize from '@dayjs/plugin-humanize';
import isNil from 'lodash/isNil';

// 注册插件
dayjs.extend(duration);
dayjs.extend(humanize);

calculateDelay(alertDate: string, operationDate: string): string | undefined {
  if (isNil(alertDate) || isNil(operationDate)) return undefined;

  const diffMs = Math.abs(dayjs(alertDate).diff(dayjs(operationDate), 'millisecond'));
  // 仅返回最大量级的单位,自动输出阿拉伯数字和正确单复数
  return dayjs.duration(diffMs).humanize({
    largest: 1,
    round: true,
    spacer: ' '
  });
}

该方案年、月差值计算更精准,完全贴合Dayjs原生逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:39:03