I'm trying to get the next 'renewal date' of a subscription model (month & year). That's my setup:
var getPeriod = 'month';
// var getPeriod = 'year';
var getEffective = '2022-06-02';
var getDate = moment('2022-08-01');
if(getPeriod == 'month'){
var getDuration = moment.duration(getDate.diff(getEffective)).months();
} else if('year'){
var getDuration = moment.duration(getDate.diff(getEffective)).years();
}
if(getDuration >= 0){
var getCounter = getDuration+1;
} else {
var getCounter = 1;
}
var getRenewalNext = moment(getEffective).add(getCounter, getPeriod+'s').format('YYYY-MM-DD');
console.log('getDuration:');
console.log(getDuration);
console.log('getRenewalNext:');
console.log(getRenewalNext);
Attempt 1: Correct
var getEffective = '2022-06-01';
var getDate = moment('2022-08-01');
"getDuration:"
2
"getRenewalNext:"
"2022-09-01"
Attempt 2: Correct
var getEffective = '2022-06-03';
var getDate = moment('2022-08-01');
"getDuration:"
1
"getRenewalNext:"
"2022-08-03"
Attempt 3: Not Correct
var getEffective = '2022-06-02';
var getDate = moment('2022-08-01');
"getDuration:"
2
"getRenewalNext:"
"2022-09-02"
For the last attempt I'm getting "2022-09-02" as the next renewal data, but I would have expected 1 more day to go and 'Next Renewal Date' to be "2022-08-02". Why so or am I missing something? How can I solve this?
That's my fiddle: https://jsfiddle.net/ja1k6owb/
Upgrading to a newer version of moment should resolve the issue.
I'm using the latest version below and we're getting the correct answer.
One should be able to find the change made (between moment 2.2.1 and 2.29.4) that fixes the issue.
var getPeriod = 'month';
// var getPeriod = 'year';
var getEffective = '2022-06-02';
var getDate = moment('2022-08-01');
if(getPeriod == 'month'){
var getDuration = moment.duration(getDate.diff(getEffective)).months();
} else if('year'){
var getDuration = moment.duration(getDate.diff(getEffective)).years();
}
if(getDuration >= 0){
var getCounter = getDuration+1;
} else {
var getCounter = 1;
}
var getRenewalNext = moment(getEffective).add(getCounter, getPeriod+'s').format('YYYY-MM-DD');
console.log('getDuration:');
console.log(getDuration);
console.log('getRenewalNext:');
console.log(getRenewalNext);
.as-console-wrapper { max-height: 100% !important; }
<script src="https://momentjs.com/downloads/moment.js"></script>