【问题标题】:Moment.js does not accepts variable as parametersMoment.js 不接受变量作为参数
【发布时间】:2016-09-04 16:28:59
【问题描述】:

我正在使用 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

因此,我无法得到确切的区别。 谁能建议我哪里出错了? 谢谢。

【问题讨论】:

    标签: javascript timestamp momentjs


    【解决方案1】:

    当您使用 + 将时刻对象转换为基元时,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多