Sapikelio Sapikelio - 1 month ago 9
Javascript Question

Why does moment.js subtract method not works?

I am trying to subtract 7 days to a given date using moment.js

var date ="2015-10-19";
var now = moment(date);
var oneWeekAgo = moment(date).subtract(7,'days');


When I check values of
now
and
oneWeekAgo
have the same content both.

Moment {_isAMomentObject: true, _i: "2015-10-19", _f: "YYYY-MM-DD ", _isUTC: false, _pf: Object…}


However, If I subtract 7 days to current time it works.

var oneWeekAgo = moment().subtract(7,'days');


I've noticed that instanciate a moment without arguments change his structure, storing date on
_d
attribute instead
_i
.

Moment {_isAMomentObject: true, _isUTC: false, _pf: Object, _locale: Locale, _d: Tue Oct 13 2015 13:34:50 GMT+0200 (Hora de verano romance)}


Why it happens? and how can I solve it?
Thanx.

Answer

Private variables of momentjs are not that simple.

_i is just the string you use to instanciate the momentjs object. It is not the current value of the date.

var date = "2015-10-19";
var now = moment(date);
var oneWeekAgo = moment(date).subtract(7, 'days');

// 2015 10 19
console.log(now.format('YYYY MM DD'));

// 2015 10 12
console.log(oneWeekAgo.format('YYYY MM DD'));