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

115
Vistas
Getting incorrect month difference between 2 dates

I have 2 dates like below :

Todays date = 2021-10-13 11:03:57.560

Old date = 2016-08-07 11:03:57.560

I want month difference from todays date Month - Old date Month = 10 - 8 = 2

Code:

console.log(moment().diff($scope.creationTime, 'months')); // returns 62

Expected: Current month - Old date month

Can anyone please help me with this?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Right now you get 62 because the two dates are 5 years and 2 months apart:

5 * 12 + 2 = 62

An easy way to drop the year difference is to use the remainder operator and do monthDifference % 12 which will give you only the number of months, regardless of the years:

function monthDiff(date1, date2) {
  const monthDifference = moment(date1).diff(moment(date2),  'months');
  return monthDifference % 12;
}


console.log(monthDiff("2021-10-13 11:03:57.560", "2016-08-07 11:03:57.560"));
console.log(monthDiff("2021-10-07 11:03:57.560", "2016-08-13 11:03:57.560"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use month() from moment.js to get the months and simple math after that:

const today = moment();
const someday = moment('2011-01-01 00:00Z');

console.log(today.month())
console.log(someday.month())

console.log(Math.abs(today.month()-someday.month()))
about 4 years ago · Juan Pablo Isaza Denunciar

0

You dont need moment to do that you use Date as well

new Date().getMonth - to get your current month
new Date('2016-08-07 11:03:57.560').getMonth() - to get the month of your old date

console.log(new Date().getMonth() - new Date('2016-08-07 11:03:57.560').getMonth())

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