How does JS calculate the month between two dates, less than one month as one month?

for example: 2018-8-16 and 2018-9-16 should be calculated as one month, 2018-8-16 and 2018-9-17 should be calculated as two months

function countHours(){
    var startTime = $("-sharpstartTime").val();
    var endTime = $("-sharpendTime").val();
    time1 = Date.parse(new Date(startTime));
    time2 = Date.parse(new Date(endTime));
    var time3 =  parseInt(Math.abs(time2 - time1) / 1000 / 60 / 60 / 24 /30) ;
    $("-sharpyearSpan").text( time3 + "");
}
Apr.15,2021

when getting time3, round up the Math.ceil (), instead of parseInt directly.


fixed for 30 days a month? Don't you consider the situation of 28, 29, 31 days

  function countMonths (start, end) {
    let startTime = new Date(start)
    let endTime = new Date(end)
    return (endTime.getYear() - startTime.getYear()) * 12 + endTime.getMonth() - startTime.getMonth() + (endTime.getDate() > startTime.getDate() ? 1 : 0)
  }
$("-sharpyearSpan").text( countMonths($("-sharpstartTime").val(),$("-sharpendTime").val()) + "")
Menu