Sapikelio Sapikelio - 1 year ago 128
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
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
attribute instead

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?

Answer Source

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'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download