Difference in Months between two dates in JavaScript

后端 未结 26 2849
南方客
南方客 2020-11-22 17:06

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

26条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 17:54

    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

提交回复
热议问题