Javascript: Subtract months from a string date using moment library

Unable to subtract months from a string date using moment library

var str = '2015-10-30'; // date in the string format
var dateMoment = moment(str)
var result = moment(dateMoment).subtract(12, 'months');
console.log('old date = ', dateMoment)
console.log('new date = ', result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Can you check in jsfiddle: jsfiddle.net/eshwar70/5f10puqa/9 ; It's not working as expected. Open the developer tools and check. I am checking on my browser it is not working as expected. –

enter image description here

Solution:

Adding .format() at the end of the function; var result = moment(dateMoment).subtract(12, 'months').format();


Solution 1:

You need go to the official documentation to understand how their internal system works. Here is the official documentation explaining why your code is not showing the expected value. Basically, it is saying the moment object is mutable. So if you are subtracting from the original date, you are actually changing the original date as well. After subtracting, please look carefully the internal structure, you will see _d value actually has changed, and you can see the result by using format().

var str = '2015-10-30';
var dateMoment = moment(str);
var result = dateMoment.clone().subtract(12, 'months').format();
console.log('old date = ', dateMoment.format())
console.log('new date = ', result)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Moment Documentation