Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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();

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

But your code works perfectly: enter image description here

The result are decreasing one year because you are subtract 12 months (1 year). So 2015-10-30 (subtract 12 months) = 2014-10-30

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!