Add a duration to a moment (moment.js)

后端 未结 3 2017
猫巷女王i
猫巷女王i 2020-11-29 22:10

Moment version: 2.0.0

After reading the docs, I thought this would be straight-forward (Chrome console):

var timestring1 = \"2013-05-09T00:00:00Z\";
         


        
3条回答
  •  孤独总比滥情好
    2020-11-29 22:23

    I think you missed a key point in the documentation for .add()

    Mutates the original moment by adding time.

    You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)

    If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.

    You can work around this behavior by cloning the moment, as described here.

    Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.

    Your code is now:

    var timestring1 = "2013-05-09T00:00:00Z";
    var timestring2 = "2013-05-09T02:00:00Z";
    var startdate = moment(timestring1);
    var expected_enddate = moment(timestring2);
    var returned_endate = moment(startdate).add(2, 'hours');  // see the cloning?
    returned_endate.isSame(expected_enddate)  // true
    

提交回复
热议问题