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

使用Moment.js的diff方法比较时间结果异常,求解决

问题原因

你创建moment对象b时,参数顺序完全错了。Moment.js的数组构造器格式是[年, 月, 日, 时, 分, 秒],你现在把当前小时(myhours)当成了月份,当前分钟(myminutes)当成了日期,这导致b的实际日期完全不符合预期,自然算出来的时间差是错的。

修正后的代码
var moment = require('moment.js')
console.show()
var mydate = new Date();

const myhours = mydate.getHours()
const myminutes = mydate.getMinutes()

// a是2007年1月29日(注意Moment的月份是0开始,0=1月)
var a = moment([2007, 0, 29]);
// b是2007年1月29日的当前时分,参数顺序修正为[年, 月, 日, 时, 分]
var b = moment([2007, 0, 29, myhours, myminutes]);

log(b.diff(a,'minutes'))
补充说明
  • Moment.js的月份参数是0索引的(0代表1月,11代表12月),你原来的a对象是正确的。
  • getHours()和getMinutes()本身返回的就是数字,不需要额外用parseInt()转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:05:19