Difference in Months between two dates in JavaScript
Asked Answered
M

29

233

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 :)

Mascia answered 29/3, 2010 at 7:34 Comment(4)
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.Adequacy
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?Metaphysic
@Metaphysic Someone needing to implement this probably won't have answers, as their manager has no idea what they're asking in the first place. :)Alvinalvina
I have created a small library to calculate the difference for two dates in terms of years, months, days, hours ... etc. Maybe useful?Cleaver
K
328

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.)

Kline answered 29/3, 2010 at 7:49 Comment(6)
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).Scaleboard
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.Austrasia
@Austrasia - 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.Kline
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.Walkerwalkietalkie
How about d1 as 2024.01.01 and d2 as 2024.12.31? In this case, your logic will return 11 months but actually, it is 12 months. @T.J.CrowderSula
@Sula That depends on how you're defining "number of months between," please see the first sentence of the answer. Adjust as you need to, the tools are there. :-)Kline
G
168

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.

Gittens answered 30/11, 2010 at 10:59 Comment(7)
This is the shortest and easiest to understand code I'd seen so far!Enclave
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.Kyle
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.Brann
Start from the fact that 2018/01 and 2017/01 are 12 months apart. Work backwards from there. This answer gets it. ;)Neighbors
Thanks! This function is very helpful for meCharissa
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!!Iso
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 monthPretonic
T
49

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);
};
Thompkins answered 14/11, 2014 at 13:22 Comment(6)
Seriously though, who voted this down? He's right, the accepted answer is just... wrong.Toni
This is the best-fit answer.Cistaceous
make this accepted answer. This more accurate than accepted one. For Example accepted answer does not calculate daysMadrigal
Crowder's accepted answer has since been updated. There may still be important differences between it and this answer, but, as of this writing, the concerns listed here have been addressed.Passable
@NicolaiHarbo, no I would say the correct answer in your example is indeed 7, therefore the function is correct. It sounds like you are looking for calendar months, which is a different concept.Victorious
@Thompkins This looks best answer for me. I want to upvote more than once. Thanks.Apprise
E
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;
Evaleen answered 1/3, 2013 at 13:25 Comment(6)
Nice one! Worked perfect for me.Overdone
For the last one, I will recommend : numberOfMonths=(year2-year1)*12+(month2-month1)+1; which does the same but is more semantically correct to meKyle
Yeah, nice and more elegant approach.Evaleen
This was the best answer. Thanks!Summon
This is simple and clean. Thank you for writing great code.Drugi
I don't see why you're incrementing the month if it's 0. The math still works either way. Maybe i'm missing something.Solemn
R
31

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://mcmap.net/q/117213/-difference-in-months-between-two-dates-in-javascript 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)
Repentance answered 9/1, 2014 at 13:2 Comment(2)
Tha's what I thought I came here for verification and that's the only answer that makes sense to meNummulite
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."Toni
S
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())
Shaitan answered 15/3, 2014 at 13:41 Comment(0)
A
8

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);
Annul answered 15/2, 2019 at 9:48 Comment(1)
You should multiply by 365.25 to take leap years into accountParatuberculosis
C
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;
    }
Ceramics answered 21/7, 2010 at 21:28 Comment(1)
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.Toni
B
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.

Benzoyl answered 18/3, 2014 at 21:33 Comment(0)
N
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.

Noctilucent answered 22/11, 2015 at 6:17 Comment(0)
T
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;
}
Toni answered 27/2, 2015 at 18:54 Comment(0)
T
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)

Travail answered 3/11, 2015 at 16:44 Comment(1)
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.Contrasty
M
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

Marisamariscal answered 29/1, 2020 at 4:8 Comment(0)
S
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;
}
Sociopath answered 7/12, 2011 at 13:30 Comment(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).Singles
O
2

This should work fine:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months += d2.getMonth() - d1.getMonth();
    return months;
}
Occultation answered 6/5, 2016 at 22:6 Comment(0)
A
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);
}
Adhesion answered 29/9, 2015 at 6:7 Comment(0)
L
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
Lavernalaverne answered 25/4, 2016 at 22:7 Comment(0)
H
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;

}

Hypno answered 16/10, 2016 at 13:17 Comment(0)
Y
1

below logic will fetch difference in months

(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
Yacano answered 16/8, 2017 at 0:1 Comment(0)
C
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;
}
Char answered 21/11, 2018 at 18:30 Comment(0)
T
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;
}
Tyrannize answered 5/7, 2021 at 7:22 Comment(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) * 12Fassold
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.Easement
A
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;
}
Agata answered 7/8, 2017 at 12:31 Comment(0)
C
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 
Cleromancy answered 8/12, 2017 at 12:21 Comment(2)
Can you add more detailed explanation of how this works? This would make the answer betterCalabro
Is there an assumption months have 30 days?Kneeland
S
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;
}
Sphinx answered 6/8, 2020 at 12:46 Comment(0)
G
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;
}
 
Geriatrics answered 9/11, 2020 at 14:8 Comment(0)
D
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;
}
Detwiler answered 22/3, 2022 at 21:30 Comment(0)
B
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>
Burnight answered 8/4, 2022 at 6:36 Comment(0)
B
-2
anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));
Breault answered 11/2, 2016 at 6:3 Comment(2)
While this code snippet may be the solution, including an explanation 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.Sherikasherill
It's not much use posting an answer that depends on functions that aren't explained or defined in the answer.Regimen
R
-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.

Ranitta answered 19/2, 2012 at 2:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.