220

How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?

Any help would be great :)

William Troup
  • 12,739
  • 21
  • 70
  • 98
  • A month is not a very accurate unit of measurement because the length of the month changes depending on which month it is. If an interval lasts 30 days between January and February, that's less than 1 month if you think in terms of a 31 day month, but more than 1 month if you consider February's 28 or 29 days. – Mark Byers Mar 29 '10 at 07:40
  • 8
    Not very well defined question. Is Feb 28 23:58 to March 1 00:01 one month? Or just one day? Or just three minutes? Or all three? – Thilo Mar 29 '10 at 07:43
  • 2
    @Thilo Someone needing to implement this probably won't have answers, as their manager has no idea what they're asking in the first place. :) – AlbertEngelB May 13 '15 at 14:54
  • I have created a [small library](https://stackblitz.com/edit/web-platform-hrkuqv?file=script.js) to calculate the difference for two dates in terms of years, months, days, hours ... etc. Maybe useful? – KooiInc Jan 04 '23 at 14:32

29 Answers29

321

The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)

You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.

For instance, off-the-cuff:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

function test(d1, d2) {
    var diff = monthDiff(d1, d2);
    console.log(
        d1.toISOString().substring(0, 10),
        "to",
        d2.toISOString().substring(0, 10),
        ":",
        diff
    );
}

test(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16

test(
    new Date(2010, 0, 1),  // January 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 2

test(
    new Date(2010, 1, 1),  // February 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 1

(Note that month values in JavaScript start with 0 = January.)

Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.

There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.


Note: There used to be a + 1 in the above, here:

months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
// −−−−−−−−−−−−−−−−−−−−^^^^
months += d2.getMonth();

That's because originally I said:

...this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in).

I've removed it for two reasons:

  1. Not counting partial months turns out not to be what many (most?) people coming to the answer want, so I thought I should separate them out.

  2. It didn't always work even by that definition. :-D (Sorry.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Great anwser! Thank you! I solved the 'there used to be `+1` in the above' problem just adding one day to d2 date (it did the trick for my scenario). – Renato Aloi Nov 10 '21 at 03:21
  • Does it make sense to add, depending on context, something like `if (d2.getDate() >= d1.getDate()) months++;`? Because if you are trying to get the duration in months between two dates it makes a difference if you are ahead or behind the day. – velop Jan 19 '22 at 09:17
  • 1
    @velop - It certainly could, depending on your definition of "the number of months in the difference." I've long since given up second-guessing the various different ways people seem to define it. The OP never did. – T.J. Crowder Jan 19 '22 at 09:19
  • You should consider to use `return Math.abs(months);` I mean it is named monthDiff and should also do the same work vice versa, when the end date is given as the first parameter. – Sercan Samet Savran Apr 19 '23 at 22:56
161

If you do not consider the day of the month, this is by far the simpler solution

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() + 
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}


//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1

Be aware that month index is 0-based. This means that January = 0 and December = 11.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • 15
    This is the shortest and easiest to understand code I'd seen so far! – Omar Sep 18 '12 at 00:26
  • Nothing complicated with this one except the fact that every month started is counted. 31/03/2011 -> 01/05/2011 will be two months as well as 01/03/2011 -> 31/05/2011 but it should be three to be exact. – Natim Sep 05 '13 at 17:05
  • If you just want to know the number of months this one is PERFECT!!!!! If you need to know based on days in the month this will not work. – OSDM Oct 05 '15 at 06:56
  • 1
    Start from the fact that 2018/01 and 2017/01 are 12 months apart. Work backwards from there. This answer gets it. ;) – Gerard ONeill Jun 21 '18 at 23:20
  • 1
    Thanks! This function is very helpful for me – Trương Long Jul 31 '19 at 05:31
  • Not a right solution. If you set the `dateFrom=Dec 13, 2020` and `dateTo=July 04, 2021` then your method will return `07`. But it must be `08`. Try it!! – Arsman Ahmad Feb 03 '22 at 18:29
  • There could be a bug. on ```dateTo.getMonth() - dateFrom.getMonth()``` what if the ```dateTo.getMonth() = 1 (february)``` and ```dateFrom.getMonth() = 7 (august)``` then the result from the first equation will be minus. to corrected this we should use abs like ```Math.Abs(dateTo.getMonth() - dateFrom.getMonth())``` so we can get the absoute distance between those two month – dariant Virgi Nov 06 '22 at 23:12
47

Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the roundUpFractionalMonths param as true, so a 3 month and 1 day difference will be returned as 4 months.

The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.

For example, monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015')) returns 0 which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.

Here's the function I wrote:

function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
    //Months will be calculated between start and end dates.
    //Make sure start date is less than end date.
    //But remember if the difference should be negative.
    var startDate=date1;
    var endDate=date2;
    var inverse=false;
    if(date1>date2)
    {
        startDate=date2;
        endDate=date1;
        inverse=true;
    }

    //Calculate the differences between the start and end dates
    var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
    var monthsDifference=endDate.getMonth()-startDate.getMonth();
    var daysDifference=endDate.getDate()-startDate.getDate();

    var monthCorrection=0;
    //If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
    //The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
    if(roundUpFractionalMonths===true && daysDifference>0)
    {
        monthCorrection=1;
    }
    //If the day difference between the 2 months is negative, the last month is not a whole month.
    else if(roundUpFractionalMonths!==true && daysDifference<0)
    {
        monthCorrection=-1;
    }

    return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};
Francisc
  • 77,430
  • 63
  • 180
  • 276
34

Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths; 

1.If you want just the number of the months between the two dates excluding both month1 and month2

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.If you want to include either of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3.If you want to include both of the months

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206
30

If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.

var months = to.getMonth() - from.getMonth() 
    + (12 * (to.getFullYear() - from.getFullYear()));

if(to.getDate() < from.getDate()){
    months--;
}
return months;

This is an extended version of the answer https://stackoverflow.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).

This will cover the following;

  • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
  • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
  • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
  • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)
Community
  • 1
  • 1
harun
  • 1,889
  • 18
  • 19
  • 2
    Tha's what I thought I came here for verification and that's the only answer that makes sense to me – Andreas Sep 07 '14 at 06:19
  • 2
    This doesn't work when comparing two months where the month is shorter. For example, from March 31st to April 30th. That's *all* of April, so the answer should be "1." – Michael Blackburn Feb 27 '15 at 18:36
8

Difference in Months between two dates in JavaScript:

 start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
 end_date = new Date(new Date(year, month, day)

total months between start_date and end_date :

 total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())
7

You could also consider this solution, this function returns the month difference in integer or number

Passing the start date as the first or last param, is fault tolerant. Meaning, the function would still return the same value.

const diffInMonths = (end, start) => {
   var timeDiff = Math.abs(end.getTime() - start.getTime());
   return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}

const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));

// shows month difference as integer/number
console.log(result);
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
6

I know this is really late, but posting it anyway just in case it helps others. Here is a function I came up with that seems to do a good job of counting differences in months between two dates. It is admittedly a great deal raunchier than Mr.Crowder's, but provides more accurate results by stepping through the date object. It is in AS3 but you should just be able to drop the strong typing and you'll have JS. Feel free to make it nicer looking anyone out there!

    function countMonths ( startDate:Date, endDate:Date ):int
    {
        var stepDate:Date = new Date;
        stepDate.time = startDate.time;
        var monthCount:int;

        while( stepDate.time <= endDate.time ) { 
            stepDate.month += 1;
            monthCount += 1;
        }           

        if ( stepDate != endDate ) { 
            monthCount -= 1;
        }

        return monthCount;
    }
James
  • 641
  • 8
  • 17
  • This is the *most likely correct* approach for most situations. There are so many exceptions and vagaries in our calendar, the best approach is to delegate handling them to a well-tested library, like Date(). For most (short) spans, this will return the same answer as the calculated approaches, but when you're dealing with long spans of time (including leap years, leap-years-that-aren't-leap-years, leap-seconds, etc) you're more likely to run into an exception where subtracting months and adding years will be incorrect. See my answer for exceptions when calculation would be best. – Michael Blackburn Nov 16 '16 at 15:39
5

To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    // edit: increment months if d2 comes later in its month than d1 in its month
    if (d2.getDate() >= d1.getDate())
        months++
    // end edit
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10

This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.

calvin
  • 481
  • 4
  • 9
5

Consider each date in terms of months, then subtract to find the difference.

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

This will get you the difference of months between the two dates, ignoring the days.

internet-nico
  • 1,637
  • 19
  • 17
4

There are two approaches, mathematical & quick, but subject to vagaries in the calendar, or iterative & slow, but handles all the oddities (or at least delegates handling them to a well-tested library).

If you iterate through the calendar, incrementing the start date by one month & seeing if we pass the end date. This delegates anomaly-handling to the built-in Date() classes, but could be slow IF you're doing this for a large number of dates. James' answer takes this approach. As much as I dislike the idea, I think this is the "safest" approach, and if you're only doing one calculation, the performance difference really is negligible. We tend to try to over-optimize tasks which will only be performed once.

Now, if you're calculating this function on a dataset, you probably don't want to run that function on each row (or god forbid, multiple times per record). In that case, you can use almost any of the other answers here except the accepted answer, which is just wrong (difference between new Date() and new Date() is -1)?

Here's my stab at a mathematical-and-quick approach, which accounts for differing month lengths and leap years. You really should only use a function like this if you'll be applying this to a dataset (doing this calculation over & over). If you just need to do it once, use James' iterative approach above, as you're delegating handling all the (many) exceptions to the Date() object.

function diffInMonths(from, to){
    var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));

    if(to.getDate() < from.getDate()){
        var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
        if (to < newFrom  && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
            months--;
        }
    }

    return months;
}
Michael Blackburn
  • 3,161
  • 1
  • 25
  • 18
4

Calculate the difference between two dates include fraction of month (days).


var difference = (date2.getDate() - date1.getDate()) / 30 +
    date2.getMonth() - date1.getMonth() +
    (12 * (date2.getFullYear() - date1.getFullYear()));

For example:
date1: 24/09/2015 (24th Sept 2015)
date2: 09/11/2015 (9th Nov 2015)
the difference: 2.5 (months)

Shneor
  • 304
  • 3
  • 4
  • What am I missing....why isn't this the best one? You can choose how to round. Math.floor() if you only want complete months. – Todd Horst Aug 03 '23 at 16:52
3

Number Of Months When Day & Time Doesn't Matter

In this case, I'm not concerned with full months, part months, how long a month is, etc. I just need to know the number of months. A relevant real world case would be where a report is due every month, and I need to know how many reports there should be.

Example:

  • January = 1 month
  • January - February = 2 months
  • November - January = 3 months

This is an elaborated code example to show where the numbers are going.

Let's take 2 timestamps that should result in 4 months

  • November 13, 2019's timestamp: 1573621200000
  • February 20, 2020's timestamp: 1582261140000

May be slightly different with your timezone / time pulled. The day, minutes, and seconds don't matter and can be included in the timestamp, but we will disregard it with our actual calculation.

Step 1: convert the timestamp to a JavaScript date

let dateRangeStartConverted = new Date(1573621200000);
let dateRangeEndConverted = new Date(1582261140000);

Step 2: get integer values for the months / years

let startingMonth = dateRangeStartConverted.getMonth();
let startingYear = dateRangeStartConverted.getFullYear();
let endingMonth = dateRangeEndConverted.getMonth();
let endingYear = dateRangeEndConverted.getFullYear();

This gives us

  • Starting month: 11
  • Starting Year: 2019
  • Ending month: 2
  • Ending Year: 2020

Step 3: Add (12 * (endYear - startYear)) + 1 to the ending month.

  • This makes our starting month stay at 11
  • This makes our ending month equal 15 2 + (12 * (2020 - 2019)) + 1 = 15

Step 4: Subtract the months

15 - 11 = 4; we get our 4 month result.

29 Month Example Example

November 2019 through March 2022 is 29 months. If you put these into an excel spreadsheet, you will see 29 rows.

  • Our starting month is 11
  • Our ending month is 40 3 + (12 * (2022-2019)) + 1

40 - 11 = 29

Community
  • 1
  • 1
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
2

This should work fine:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months += d2.getMonth() - d1.getMonth();
    return months;
}
Jordan Ferr
  • 191
  • 2
  • 11
2

Here you go other approach with less looping:

calculateTotalMonthsDifference = function(firstDate, secondDate) {
        var fm = firstDate.getMonth();
        var fy = firstDate.getFullYear();
        var sm = secondDate.getMonth();
        var sy = secondDate.getFullYear();
        var months = Math.abs(((fy - sy) * 12) + fm - sm);
        var firstBefore = firstDate > secondDate;
        firstDate.setFullYear(sy);
        firstDate.setMonth(sm);
        firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
        return months;
}
ggomeze
  • 5,711
  • 6
  • 29
  • 32
  • 1
    beware of this method : it (pretty obviously when you read it carefully) mutates the first date which is passed back to the caller (as dates are passed by reference). – Andiih Jul 15 '16 at 13:47
1
function calcualteMonthYr(){
    var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
    var toDate = new Date($('#txtDurationTo2').val());

var months=0;
        months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
        months -= fromDate.getMonth();
        months += toDate.getMonth();
            if (toDate.getDate() < fromDate.getDate()){
                months--;
            }
    $('#txtTimePeriod2').val(months);
}
1

Following code returns full months between two dates by taking nr of days of partial months into account as well.

var monthDiff = function(d1, d2) {
  if( d2 < d1 ) { 
    var dTmp = d2;
    d2 = d1;
    d1 = dTmp;
  }

  var months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth() + 1;
  months += d2.getMonth();

  if( d1.getDate() <= d2.getDate() ) months += 1;

  return months;
}

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0

monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0
Delorean
  • 356
  • 3
  • 11
1
function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
    var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
          diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24))); 
    d1new = new Date(d2year, d2month, 1,0,0,0,0);
    d1new.setDate(d1new.getDate()-1);
    d1maxday = d1new.getDate();
    months += diffdate / d1maxday;
}
else
{
      if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
    {
        months += 1;
    }
    diffdate = d2day - d1day + 1;
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
    d2new.setDate(d2new.getDate()-1);
    d2maxday = d2new.getDate();
    months += diffdate / d2maxday;
}

return months;

}

Tariq
  • 11
  • 1
1

below logic will fetch difference in months

(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
Anoop Isaac
  • 932
  • 12
  • 15
1
function monthDiff(date1, date2, countDays) {

  countDays = (typeof countDays !== 'undefined') ?  countDays : false;

  if (!date1 || !date2) {
    return 0;
  }

  let bigDate = date1;
  let smallDate = date2;

  if (date1 < date2) {
    bigDate = date2;
    smallDate = date1;
  }

  let monthsCount = (bigDate.getFullYear() - smallDate.getFullYear()) * 12 + (bigDate.getMonth() - smallDate.getMonth());

  if (countDays && bigDate.getDate() < smallDate.getDate()) {
    --monthsCount;
  }

  return monthsCount;
}
Abbas Siddiqi
  • 391
  • 2
  • 8
1

This is the simplest solution I could find. This will directly return the number of months. Although, it always gives an absolute value.

new Date(new Date(d2) - new Date(d1)).getMonth();

For non-absolute values, you can use the following solution:

function diff_months(startDate, endDate) {
  let diff = new Date( new Date(endDate)  - new Date(startDate) ).getMonth();
  return endDate >= startDate ? diff : -diff;
}
Ankur Kedia
  • 3,453
  • 1
  • 13
  • 15
  • 2
    very good solution. When the diff is more than one year, don't forget to add the years with something like `(diff.getFullYear() - 1970) * 12` – Datz Jul 20 '21 at 13:17
  • 1
    Beware this easy-seeming solution: when you do `Date - Date`, you get a integer number of seconds. Wrapping this in a `new Date` will give you some date on or after Jan 1970, which you would then be getting the ordinal month from. This would work if we had an equal number of days in each month, but we don't. – sam-w Dec 29 '22 at 02:48
0

See what I use:

function monthDiff() {
    var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
    var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
    var months = 0;
    while (startdate < enddate) {
        if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
            months++;
            startdate.addMonths(1);
            startdate.addDays(2);
        } else {
            months++;
            startdate.addMonths(1);
        }
    }
    return months;
}
0

It also counts the days and convert them in months.

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
    months -= d1.getMonth() + 1; 
    months += d2.getMonth();  //calculates number of complete months between two months
    day1 = 30-d1.getDate();  
    day2 = day1 + d2.getDate();
    months += parseInt(day2/30);  //calculates no of complete months lie between two dates
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
    new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
);
//return value will be 4 months 
0
getMonthDiff(d1, d2) {
    var year1 = dt1.getFullYear();
    var year2 = dt2.getFullYear();
    var month1 = dt1.getMonth();
    var month2 = dt2.getMonth();
    var day1 = dt1.getDate();
    var day2 = dt2.getDate();
    var months = month2 - month1;
    var years = year2 -year1
    days = day2 - day1;
    if (days < 0) {
        months -= 1;
    }
    if (months < 0) {
        months += 12;
    }
    return months + years*!2;
}
Singhak
  • 8,508
  • 2
  • 31
  • 34
0

Any value is returned along with its absolute value.

function differenceInMonths(firstDate, secondDate) {
    if (firstDate > secondDate) [firstDate, secondDate] = [secondDate, firstDate];
    let diffMonths = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
    diffMonths -= firstDate.getMonth();
    diffMonths += secondDate.getMonth();
    return diffMonths;
}
 
Ozan ISIK
  • 1
  • 1
0

The following code snippet helped me to find months between two dates

Find Months Count Between two dates JS


Months Between two dates JS

Code Snippet

function diff_months_count(startDate, endDate) {
    var months;
    var d1 = new Date(startDate);
    var d2 = new Date(endDate);
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}
DSquare
  • 2,458
  • 17
  • 19
Abdul Rehman
  • 142
  • 1
  • 12
0

#Here is a nice piece of code i wrote for getting number of days and months from given dates

[1]: jsfiddle link

/**
 * Date a end day
 * Date b start day
 * @param DateA Date @param DateB Date
 * @returns Date difference
 */
function getDateDifference(dateA, DateB, type = 'month') {
  const END_DAY = new Date(dateA)
  const START_DAY = new Date(DateB)
  let calculatedDateBy
  let returnDateDiff
  if (type === 'month') {
    const startMonth = START_DAY.getMonth()
    const endMonth = END_DAY.getMonth()
    calculatedDateBy = startMonth - endMonth
    returnDateDiff = Math.abs(
      calculatedDateBy + 12 * (START_DAY.getFullYear() - END_DAY.getFullYear())
    )
  } else {
    calculatedDateBy = Math.abs(START_DAY - END_DAY)
    returnDateDiff = Math.ceil(calculatedDateBy / (1000 * 60 * 60 * 24))
  }
  const out = document.getElementById('output')
  out.innerText = returnDateDiff
  return returnDateDiff
}
// Gets number of days from given dates
/* getDateDifference('2022-03-31','2022-04-08','day') */
// Get number of months from given dates
getDateDifference('2021-12-02','2022-04-08','month')
<div id="output"> </div>
-2
anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • 3
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Eugene Podskal Aug 01 '19 at 11:28
  • It's not much use posting an answer that depends on functions that aren't explained or defined in the answer. – RobG Aug 05 '19 at 05:07
-8

One approach would be to write a simple Java Web Service (REST/JSON) that uses JODA library

http://joda-time.sourceforge.net/faq.html#datediff

to calculate difference between two dates and call that service from javascript.

This assumes your back end is in Java.

Ravi Chinoy
  • 165
  • 1
  • 5
  • 11