这就是我所拥有的,我想将其变成多维数组
var calculateDates = function(date1, date2) {
var dt1 = new Date(date1);
var dt2 = new Date(date2);
return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) / (1000 * 60 * 60 * 24));
}
var startDate = ["10 Jan 1982", "05 Mar 1990", "28 Dec 2001"];
var endDate = ["25 Jan 1982", "06 Mar 1990", "02 Jan 2002"];
var totalDays = 0;
for (var i = 0; i < startDate.length; i++) {
var days = calculateDates(startDate[i], endDate[i]);
console.log("Number of days between", startDate[i], "and", endDate[i], "is", days);
totalDays += days;
}
console.log("Total number of days:", totalDays);
您可以创建日期对对象的数组。您还可以将每对的结果存储在那里。
var calculateDates = function(date1, date2) {
var dt1 = new Date(date1);
var dt2 = new Date(date2);
return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) - Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) / (1000 * 60 * 60 * 24));
}
var dates = [{
startDate: "10 Jan 1982",
endDate: "25 Jan 1982"
},
{
startDate: "05 Mar 1990",
endDate: "06 Mar 1990",
},
{
startDate: "28 Dec 2001",
endDate: "02 Jan 2002"
}
]
function calculateArray(dates) {
for (var i = 0; i < dates.length; i++) {
var { startDate, endDate } = dates[i];
var days = calculateDates(startDate, endDate);
dates[i].diff = days;
}
return dates;
}
var result = calculateArray(dates);
console.log(result)
console.log("Total number of days:", result.reduce(function(agg, item) {
return agg + item.diff
}, 0));
.as-console-wrapper { min-height: 100%; }