如何在 javascript 中按月计算两个日期之间的天数

how to calculate days between two dates monthwise in javascript

我遇到了一个问题,我想计算 bootstrap daterangepicker 月份的两个选定日期之间的天数,即 让我们假设

start date = 07/19/2018 
end date  = 09/28/2018

结果应该是:

number of days in 07 = 13 days
number of days in 08 = 31 days
number of days in 09 = 28 days
total number of days = 72 days

只需比较并转换为日期。

(new Date("09/28/2018").getTime() - new Date("07/19/2018").getTime())/(24*60*60*1000) + 1

您可以使用以下代码获取总天数。

let str = new Date("07/19/2018");
let end = new Date("09/28/2018");
let totalDays = (end.getTime() - str.getTime()) / (1000 * 60 * 60 * 24);

要按月计算天数,您必须将日期、月份和年份作为单独的输入,并通过每次将月份递增 1 来计算天数,直到日期不超过结束日期。

简单的方法...(但是很慢)

var date1 = new Date('07/19/2018'),
    date2 = new Date('09/28/2018'),
    tmp_date;
if (date1 > date2) {
    tmp_date = date1;
    date1 = date2;
    date2 = tmp_date;
}

var tmp_date = date1,
    out_date = new Date(+date2 + 86400000),
    date_map = {}, year, month, date, total_days = 0;
while (+tmp_date < +out_date) {
    year = tmp_date.getFullYear();
    month = tmp_date.getMonth() + 1;
    date = tmp_date.getDate();
    if (!date_map[year]) {
        date_map[year] = {};
    }
    if (!date_map[year][month]) {
        date_map[year][month] = 1;
    } else {
        ++date_map[year][month];
    }
    tmp_date = new Date(+tmp_date + 86400000);
    ++total_days;
}

for (var year in date_map) {
    for (var month in date_map[year]) {
        console.log('number of days in ' + year + '/' + month + ' = ' + date_map[year][month] + ' days');
    }
}
console.log('total number of days = ' + total_days + ' days');

console.log(date_map);
console.log(total_days);

@Jason 先于我,但这是我的较短版本。

let start = new Date("07/19/2018");
let end = new Date("09/28/2018");
let div = new Date(start.getFullYear(), start.getMonth() + 1, 1);
while (end.getFullYear() !== start.getFullYear() || end.getMonth() !== start.getMonth()) {
 console.log((div.getTime() - start.getTime()) / (1000 * 3600 * 24));
 start = new Date(div.getTime());
 div.setMonth(div.getMonth() + 1);
}
console.log((end.getTime() - start.getTime()) / (1000 * 3600 * 24));

在末尾加1表示包含。