quma
quma

Reputation: 5733

Javascript moment - subtract month at year transition

I use moment at my javascript application and my code looks like this (at bottom) When vm.reportMonth is 1 (Januar) and vm.reportYear is e.g. 2017 and the function oneMonthBack is invoced that previousDate should be december 2016, but it is still january 2017. What I am doing wrong?

function oneMonthBack() { 
    var currentDate = moment().set('month', vm.reportMonth).set('year', vm.reportYear);
    var previousDate = currentDate.subtract(1, 'months');
    var month = previousDate.get('month');
    var year = previousDate.year();
    vm.reportMonth = month;
    vm.reportYear = year;

Upvotes: 0

Views: 668

Answers (1)

T30
T30

Reputation: 12222

I think that the subtract function is acting directly on the currentDate value, no need to assign the return value to previousDate:

var currentDate = moment().set('month', vm.reportMonth).set('year', vm.reportYear);
currentDate.subtract(1, 'months');
var month = currentDate.get('month');

Upvotes: 2

Related Questions