← 中文资源

简体中文版本

Luxon 区间与时长日历运算

用 Luxon 的 Interval 与 Duration 建模日历感知的时间段:按月计数、判断区间重叠、时长换算与人性化输出。

阅读英文原文

示例说明

账单周期、迭代窗口这类业务时间不是固定毫秒数——一个月可能是 28 到 31 天。Luxon 的 Interval 表示两个时刻之间的区间,count 方法按日历单位统计跨越的整月数;Duration 表示带单位的时长,as 方法在单位间换算。两者配合能正确处理月度报表与排期重叠检测。

技术要点

  • Interval.count 按日历月统计跨度
  • overlaps 检测两个区间是否相交
  • Duration.as 在分钟、小时等单位间换算

代码解读

span 由一月中旬到十月下旬构成,count 返回跨越的日历月数量而非近似除法;isBefore 判断整个区间是否早于当前时刻。sprint 区间演示重叠检测。budget 用 Duration.fromObject 组合小时与分钟,as 统一折算成分钟数,toISO 输出标准区间表示便于持久化。

使用建议

区间端点语义(开闭)要在团队内约定统一,Luxon 的 Interval 是左闭右开。跨时区的区间运算先统一到同一时区再比较。人机展示用 toHuman 配合 locale,不要手拼字符串。

代码示例

import { DateTime, Interval, Duration } from 'luxon';

const start = DateTime.fromISO('2026-01-15', { zone: 'utc' });
const end = DateTime.fromISO('2026-10-22', { zone: 'utc' });

const span = Interval.fromDateTimes(start, end);
console.log('months covered:', span.count('months'));
console.log('is before now:', span.isBefore(DateTime.utc()));

const sprint = Interval.fromDateTimes(
  DateTime.fromISO('2026-10-01'),
  DateTime.fromISO('2026-10-15'),
);
console.log('overlaps sprint:', span.overlaps(sprint));

const elapsed = Duration.fromMillis(span.length('milliseconds'));
console.log('quarters:', Math.floor(elapsed.as('quarters')));

const budget = Duration.fromObject({ hours: 3, minutes: 45 });
console.log('budget in minutes:', budget.as('minutes'));

const iso = span.toISO();
console.log('iso interval:', iso);