Difference in Months between two dates in JavaScript

后端 未结 26 2581
南方客
南方客 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:53
    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;
    }
    
    0 讨论(0)
  • 2020-11-22 17:54
    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);
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 17:55
    anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));
    
    0 讨论(0)
  • 2020-11-22 17:57

    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)

    0 讨论(0)
  • 2020-11-22 17:58

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

    0 讨论(0)
提交回复
热议问题