我如何在JavaScript中计算出两个Date()对象的差异,而只返回差异中的月份数?
任何帮助都是最好的:)
我如何在JavaScript中计算出两个Date()对象的差异,而只返回差异中的月份数?
任何帮助都是最好的:)
当前回答
这应该可以正常工作:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months += d2.getMonth() - d1.getMonth();
return months;
}
其他回答
有时你可能想要得到两个日期之间的月份数量,完全忽略日期部分。例如,如果你有两个日期——2013/06/21和2013/10/18——你只关心2013/06和2013/10部分,下面是场景和可能的解决方案:
var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
month1++;
month2++;
}
var numberOfMonths;
1.如果您只想知道两个日期之间的月份数,不包括第1个月和第2个月
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
2.如果你想包括这两个月中的任何一个
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
3.如果你想包括这两个月
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
#这是我写的一段很好的代码,用于获取天数和月份 从给定日期开始
把你的手
/** * 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>
下面的代码片段帮助我找到两个日期之间的月份
找到两个日期之间的月份计数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;
}
这是我能找到的最简单的解。这将直接返回月数。尽管,它总是给出一个绝对值。
new Date(new Date(d2) - new Date(d1)).getMonth();
对于非绝对值,您可以使用以下解决方案:
function diff_months(startDate, endDate) {
let diff = new Date( new Date(endDate) - new Date(startDate) ).getMonth();
return endDate >= startDate ? diff : -diff;
}
如果你需要计算完整的月份,不管这个月是28、29、30还是31天。下面应该可以。
var months = to.getMonth() - from.getMonth()
+ (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
months--;
}
return months;
这是答案https://stackoverflow.com/a/4312956/1987208的扩展版本,但修复了从1月31日到2月1日(1天)计算1个月的情况。
这将包括以下内容;
1月1日至1月31日—> 30天—>将导致0(逻辑上,因为它不是一个完整的月) 2月1日至3月1日-> 28或29天->将导致1(逻辑上,因为它是一个完整的月) 2月15日至3月15日-> 28或29天->将导致1(逻辑上,因为一个月过去了) 1月31日至2月1日-> 1天->结果为0(明显,但在1个月后的结果中提到的答案)