JavaScript中两个日期之间的月份差异

224

在JavaScript中,如何计算两个Date()对象之间的差异,并仅返回差异的月数?

任何帮助都将是极好的 :)


一个月并不是非常准确的计量单位,因为月份的长度取决于哪个月。如果在一月和二月之间有一个持续30天的间隔,那么如果你按照31天的月份来考虑,那就不到1个月,但如果你考虑2月的28或29天,那就超过了1个月。 - Mark Byers
8
这个问题定义得不太清楚。2月28日23:58到3月1日00:01是一个月吗?还是只有一天?或者只有三分钟?或者三者都是? - Thilo
2
@Thilo 可能需要实现这个的人可能没有答案,因为他们的经理首先不知道他们在问什么。 :) - AlbertEngelB
我创建了一个小型库,用于计算两个日期之间的差,以年、月、日、小时等形式。也许有用? - KooiInc
29个回答

1
以下逻辑将获取月份差异。
(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())

0
它还会计算天数并将其转换为月份。
function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
    months -= d1.getMonth() + 1; 
    months += d2.getMonth();  //calculates number of complete months between two months
    day1 = 30-d1.getDate();  
    day2 = day1 + d2.getDate();
    months += parseInt(day2/30);  //calculates no of complete months lie between two dates
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
    new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
);
//return value will be 4 months 

你能否添加更详细的解释说明这是如何工作的吗?这将使答案更好。 - serge1peshcoff
假设一个月有30天吗? - Ben Taliadoros

0
以下代码片段帮助我找到了两个日期之间的月份

在JS中查找两个日期之间的月份数


两个日期之间的月份差异 JS 代码片段
function diff_months_count(startDate, endDate) {
    var months;
    var d1 = new Date(startDate);
    var d2 = new Date(endDate);
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

0

#这是我写的一个不错的代码片段,用于获取给定日期之间的天数和月数

[1]: jsfiddle链接

/**
 * Date a end day
 * Date b start day
 * @param DateA Date @param DateB Date
 * @returns Date difference
 */
function getDateDifference(dateA, DateB, type = 'month') {
  const END_DAY = new Date(dateA)
  const START_DAY = new Date(DateB)
  let calculatedDateBy
  let returnDateDiff
  if (type === 'month') {
    const startMonth = START_DAY.getMonth()
    const endMonth = END_DAY.getMonth()
    calculatedDateBy = startMonth - endMonth
    returnDateDiff = Math.abs(
      calculatedDateBy + 12 * (START_DAY.getFullYear() - END_DAY.getFullYear())
    )
  } else {
    calculatedDateBy = Math.abs(START_DAY - END_DAY)
    returnDateDiff = Math.ceil(calculatedDateBy / (1000 * 60 * 60 * 24))
  }
  const out = document.getElementById('output')
  out.innerText = returnDateDiff
  return returnDateDiff
}
// Gets number of days from given dates
/* getDateDifference('2022-03-31','2022-04-08','day') */
// Get number of months from given dates
getDateDifference('2021-12-02','2022-04-08','month')
<div id="output"> </div>


0

返回任何值及其绝对值。

function differenceInMonths(firstDate, secondDate) {
    if (firstDate > secondDate) [firstDate, secondDate] = [secondDate, firstDate];
    let diffMonths = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
    diffMonths -= firstDate.getMonth();
    diffMonths += secondDate.getMonth();
    return diffMonths;
}
 

0
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

看看我使用了什么:

function monthDiff() {
    var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
    var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
    var months = 0;
    while (startdate < enddate) {
        if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
            months++;
            startdate.addMonths(1);
            startdate.addDays(2);
        } else {
            months++;
            startdate.addMonths(1);
        }
    }
    return months;
}

-2
anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));

3
尽管这段代码片段可能是解决方案,但包括解释真正有助于提高您发布的质量。请记住,您正在为未来的读者回答问题,这些人可能不知道您提出代码建议的原因。 - Eugene Podskal
发布一个答案,如果其中依赖的函数没有在该答案中解释或定义,那么这个答案就没什么用处。 - RobG

-8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接