使用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
相关产品推荐
相关产品推荐

