JavaScript: Get time differences in months between two dates
JavaScript Datetime: Exercise-48 with Solution
Time Diff in Months
Write a JavaScript function to get time differences in months between two dates.
Test Data:
dt1 = new Date("June 13, 2014 08:11:00");
dt2 = new Date("October 19, 2014 11:13:00");
console.log(diff_months(dt1, dt2));
5
Sample Solution:
JavaScript Code:
Output:
0 5
Explanation:
In the exercise above,
- The "diff_months()" function takes two Date objects, 'dt2' and 'dt1', as parameters.
- Inside the function, it calculates the difference in milliseconds between the two dates using the "getTime()" method.
- It then converts the difference from milliseconds to months by dividing it successively by the number of milliseconds in an hour, a day, a week, and approximately 4 weeks in a month.
- The result is rounded to the nearest integer using "Math.round()" to get the whole number of months.
- Finally, the absolute value of the rounded difference is returned.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that calculates the difference in months between two dates by comparing year and month values.
- Write a JavaScript function that adjusts for the day differences when computing the month difference.
- Write a JavaScript function that returns the month difference as an integer, rounding down partial months.
- Write a JavaScript function that validates the input dates and computes the total months difference combining year and month parts.
Go to:
PREV : Time Diff in Weeks.
NEXT : Time Diff in Years.
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.