Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda