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

Moment.js isBetween方法在Date对象上未按预期工作问题排查

为什么moment的isBetween判断日期是否为明天返回false?

我有一个Date对象,想要检查它是否为明天:

const dateToCheck: Date //Sat Jun 01 2024 09:00:00 GMT-0700

我通过以下方式计算明天的日期:

const tomorrow = moment().add(1, 'day')

并获取明天的开始和结束时间:

tomorrow.startOf('day') //Sat Jun 01 2024 00:00:00 GMT-0700
tomorrow.endOf('day') //Sat Jun 01 2024 23:59:59 GMT-0700

但用isBetween检查时返回false:

var isTomorrow = moment(dateToCheck).isBetween(
  tomorrow.startOf('day'),
  tomorrow.endOf('day'),
)
console.log(isTomorrow) //false

按道理dateToCheck处于明天的时间范围内,应该返回true,请问哪里出错了?


问题出在moment.js的方法是可变的(会直接修改原对象)。

你创建的tomorrow是一个moment实例,当你调用tomorrow.startOf('day')时,这个实例已经被修改为明天的00:00:00;紧接着调用tomorrow.endOf('day'),这个实例又被修改为明天的23:59:59。

到了isBetween方法里,你再次调用tomorrow.startOf('day'),此时tomorrow又被改回00:00:00,而第二个参数tomorrow.endOf('day')会立即把tomorrow又改成23:59:59。这就导致isBetween接收的两个参数,本质上是同一个对象的两次修改后的状态,moment在比较时出现了判断偏差。

解决方案

你需要创建两个独立的moment实例,分别存储明天的开始和结束时间,避免修改同一个对象:

// 先创建明天的基准moment
const tomorrowBase = moment().add(1, 'day');
// 克隆基准对象并设置为当天开始
const tomorrowStart = tomorrowBase.clone().startOf('day');
// 克隆基准对象并设置为当天结束
const tomorrowEnd = tomorrowBase.clone().endOf('day');

const isTomorrow = moment(dateToCheck).isBetween(tomorrowStart, tomorrowEnd);
console.log(isTomorrow); // true

或者直接链式调用时避免复用原对象:

const isTomorrow = moment(dateToCheck).isBetween(
  moment().add(1, 'day').startOf('day'),
  moment().add(1, 'day').endOf('day')
);

这样就能正确判断日期是否处于明天的时间范围内了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:58:28