Moment.js不接受变量作为参数

Moment.js does not accepts variable as parameters

本文关键字:参数 变量 js 不接受 Moment      更新时间:2023-09-26

我正在使用moment.js来查找两个间隔之间的时间差。

这是我的JS代码:

console.log("from_url "+from_url); //prints: 2016-05-03T10:00:00
var a = moment(from_url);
console.log("a "+a); //prints : 1462294800000 isntead of 2016-05-03T10:00:00

因此,我无法得到确切的区别。有人能告诉我哪里出了问题吗?谢谢

当您使用+将moment对象转换为基元时,Object.prototype.valueOf()已被重写以产生以毫秒为单位的unix时间戳,或者ES2015标准所称的"时间值"。因此,你看到的是正在打印出来的价值。

如果你想要日期,只需使用.format():

var a = moment("2016-05-03T10:00:00"); "a " + a.format()
"a 2016-05-03T10:00:00-05:00"

请注意,格式需要许多参数:http://momentjs.com/docs/#/displaying/format/

就寻找两个日期和时间之间的差异而言,您应该构建两个矩,并使用矩的.diff()函数进行比较:http://momentjs.com/docs/#/displaying/difference/

例如,要获得约会和现在之间的小时差:

moment("2016-05-03T10:00:00").diff(moment(), 'hours')
-155