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

123
Views
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 answers
Answer question

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 Report

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 Report

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 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!