Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a duration to a moment (moment.js)

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";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = startdate.add(moment.duration(2, 'hours'));
returned_endate == expected_enddate  // false
returned_endate  // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}

This is a trivial example, but I can't even get it to work. I feel like I'm missing something big here, but I really don't get it. Even this this doesn't seem to work:

startdate.add(2, 'hours')
    // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}

Any help would be much appreciated.

Edit: My end goal is to make an binary status chart like the one I'm working on here: http://bl.ocks.org/phobson/5872894

As you can see, I'm currently using dummy x-values while I work through this issue.

like image 683
Paul H Avatar asked Oct 15 '22 02:10

Paul H


1 Answers

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
like image 115
Matt Johnson-Pint Avatar answered Nov 03 '22 02:11

Matt Johnson-Pint