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

从Moment迁移至Luxon时遇diff方法调用错误求助

解决Luxon迁移中「diff is not a function」的错误

问题根源

你在代码里调用了.toJSDate(),把Luxon的DateTime实例转换成了原生JavaScript的Date对象,而原生Date并没有diff方法——这就是Chrome控制台报错和VS Code类型提示警告的原因。

修正方案

  1. 保留Luxon的DateTime实例,不要转换成原生Date,直接使用Luxon自带的diff方法
  2. Luxon的diff方法本身会返回Duration对象,无需再用Duration.fromMillis二次包装

修正后的代码

const timezone = 'Europe/Lisbon';
// 注意:空字符串无法解析为有效ISO日期,建议传入格式正确的日期字符串,比如'2024-05-20T10:30:00'
const checkInString = '2024-05-20T10:30:00';

// 保留Luxon DateTime实例,不转换为原生Date
const checkIn = DateTime.fromISO(checkInString, { zone: timezone });
// 直接调用diff获取Duration,再转换为分钟数
const currentDuration = checkIn.diff(DateTime.utc()).as('minutes');

console.log(`This current time luxon: `, currentDuration);

额外注意

如果checkInString是空字符串,DateTime.fromISO会生成一个无效的DateTime实例,后续调用diff也会报错,务必确保传入的是符合ISO 8601标准的有效日期字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:31:05