0

This is my code:

var date1 = '01/02/2017';
var date2 = '31/01/2020';

var startDate   = new Date( date1.split("/")[2], date1.split("/")[1]-1, date1.split("/")[0] );
var endDate     = new Date( date2.split("/")[2], date2.split("/")[1]-1, date2.split("/")[0] );

var diff = new Date(endDate - startDate);
var diffResult = ((diff.getFullYear() - 1970) * 12+ diff.getMonth()) + " months";

so the output is only 35 months (and also 30 days but its hidden) but as 30 days are actually already a month, I would like to have it as 36 months. any suggestions?

thanks

gyula
  • 229
  • 3
  • 7
  • 12

1 Answers1

1

There are several good thoughts/solutions in the comments. It seems what you're really after is the number of 30-day intervals that fit between the start and end date.

After all, 30 days is not always a month as months can have 31 days.

If you're interested in how many 30-day intervals fit between a start and end date you can count the days and divide by 30:

var date1 = '01/02/2017';
var date2 = '31/01/2020';

var dateRegex  = /\d+/g;
var date1Array = date1.match(dateRegex);
var date2Array = date2.match(dateRegex);

var startDate  = new Date(date1Array[2], date1Array[1], date1Array[0]);
var endDate    = new Date(date2Array[2], date2Array[1], date2Array[0]);

var diffResult = Math.round((endDate-startDate)/(1000*60*60*24));

var months = Math.floor(diffResult/30);

alert(months);

Credit for the equation to get the number of days goes to this question.

Community
  • 1
  • 1
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184