Difference in Months between two dates in JavaScript

后端 未结 26 2846
南方客
南方客 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

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

提交回复
热议问题