JSFiddle - React, Tailwind, and code Playground
JavaScript
var totalDays = 0;
var fromDateText = '0001-07-01';
var toDateText = '2019-07-05';
// Parse date text
// Of course I considered using Date class, however it seems to be not able to set 0001 year... for example I write new Date(1, 1, 1), Date class returns 1901 year.
var splittedFromDate = fromDateText.split('-');
var fromDate = {
year: parseInt(splittedFromDate[0]),
month: parseInt(splittedFromDate[1]),
day: parseInt(splittedFromDate[2])
};
var splittedToDate = toDateText.split('-');
var toDate = {
year: parseInt(splittedToDate[0]),
month: parseInt(splittedToDate[1]),
day: parseInt(splittedToDate[2])
};
// Calculate totally days
for (var i = fromDate.year; i <= toDate.year; i++) {
var year = i;
for (var j = 1; j <= 12; j++) {
var month = j;
if (year == fromDate.year && month < fromDate.month) {
continue;
} else if (year == toDate.year && month > toDate.month) {
continue;
} else {
var daysPerMonth = getDaysPerMonth(year, month);
if (year == fromDate.year && month == fromDate.month) {
totalDays += daysPerMonth - fromDate.day;
} else if (year == toDate.year && month == toDate.month) {
totalDays += toDate.day;
} else {
totalDays += daysPerMonth;
}
}
}
}
console.log(totalDays); // 739081
function getDaysPerMonth(year, month) {
if (month in [2, 4, 6, 9, 11]) {
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
} else {
return 30;
}
} else {
return 31;
}
}
function isLeapYear(year) {
if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else if (year % 4 == 0) {
return true;
} else {
return false;
}
}