Home > Mobile >  How many novembers (or any particular month) are there between a start date and end date?
How many novembers (or any particular month) are there between a start date and end date?

Time:01-13

I have a very particular issue I need to solve.

I need to know how many November months (or for that matter any particular month) that exists between two date times. I can use the moment library to calculate how many months total exists between the dates, but I have no way of knowing how many of those happen to be November months.

This is important because certain months have 28 days, and other months have 30 or 31 days, and my particular use case needs to know how many of a particular month exists between the dates.

I could potentially create a loop from the start date using moment library and keep adding 1 month at a time and read what month it happens to be on and when it's November create a counter, but this feels very inefficient, especially when I'm adding a unit of time like minutes to a start time (which I am in my use case).

I can't simply convert minutes to how many months because again a month is subjective so there is no easy math conversion.

How would I go about solving this problem in an efficient manner?

CodePudding user response:

after getting how many months is there between the two dates.

  1. get how many months you need to get to the next particular month from and
  2. subtract the number of months need for the next particular month from the total months you got
  3. divide the result by 12
  4. add 1 to the result and you are done
date1 = 21-07-2022
date2= 25-01-2025
// my particular month is November
monthsBetween = 29 months
monthsForNext = 3 months
howManyNovember = ((monthsBetween -  monthsForNext) / 12 )   1
which is ((29-3) / 12 )   1 = 3
// November 2022, November 2023, November 2024

CodePudding user response:

Javascript has a getMonth() function for dates which means you can get the number of months with this little math tric that I lifted from W3Schools

endDate.getMonth() - startDate.getMonth()   12 * (endDate.getFullYear() - startDate.getFullYear())

So then the only other thing to figure out was "what month did you start on and what month did you end on so we know if there's an 11 in the range or not, so I did some simple math and came up with this:

var startdate = new Date("2002/11/21")
var enddate = new Date("2022/12/01")

console.log(getMonthDifference(startdate, enddate))

function getMonthDifference(startDate, endDate) {
    months = Math.round((endDate.getMonth() - startDate.getMonth()   12 * (endDate.getFullYear() - startDate.getFullYear())) /12)
    if (startDate.getMonth() > 11) { months = months -1 }
    if (endDate.getMonth() < 10) { months = months -1 }
    return months
}

This includes if you end on 11.

  • Related