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

如何在Luxon中比较Duration和Interval对象的大小?

解决方案

查找数组中最长的Interval

你不需要先手动转换为Duration再比较,直接调用Interval实例的length()方法获取指定单位下的长度数值,直接比较数值即可实现需求,示例代码如下:

import { Interval } from 'luxon';

// 你的Interval数组
const intervalList = [
  Interval.fromDateParts(2024, 1, 1, 2024, 1, 5),
  Interval.fromDateParts(2024, 2, 1, 2024, 2, 15),
  Interval.fromDateParts(2024, 3, 1, 2024, 3, 7)
];

// 以毫秒为统一单位比较,也可替换为秒、小时、天等其他单位
const longestInterval = intervalList.reduce((prevMax, current) => {
  return current.length('milliseconds') > prevMax.length('milliseconds') ? current : prevMax;
});

通用比较规则

  • 比较两个Interval的长度:调用length(单位)方法将Interval转换为对应单位的数值后直接比较即可,需保证两个Interval比较时使用相同单位。
  • 比较两个Duration的大小:调用as(单位)方法将Duration转换为对应单位的数值后直接比较即可,示例如下:
import { Duration } from 'luxon';

const durationA = Duration.fromObject({ days: 3 });
const durationB = Duration.fromObject({ hours: 70 });

// 比较毫秒数,3天=72小时>70小时,输出true
console.log(durationA.as('milliseconds') > durationB.as('milliseconds'));

注意:如果Duration包含年、月这类长度不固定的单位,建议统一转换为毫秒或天这类确定单位后再比较,避免出现逻辑歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:05