Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda