dateDifference static method
dateDifference method
Implementation
static AgeDuration dateDifference(
{required DateTime fromDate,
required DateTime toDate,
bool includeToDate = false}) {
// Check if toDate to be included in the calculation
DateTime endDate =
(includeToDate) ? toDate.add(const Duration(days: 1)) : toDate;
int years = endDate.year - fromDate.year;
int months = 0;
int days = 0;
if (fromDate.month > endDate.month) {
years--;
months = (DateTime.monthsPerYear + endDate.month - fromDate.month);
if (fromDate.day > endDate.day) {
months--;
days = daysInMonth(fromDate.year + years,
((fromDate.month + months - 1) % DateTime.monthsPerYear) + 1) +
endDate.day -
fromDate.day;
} else {
days = endDate.day - fromDate.day;
}
} else if (endDate.month == fromDate.month) {
if (fromDate.day > endDate.day) {
years--;
months = DateTime.monthsPerYear - 1;
days = daysInMonth(fromDate.year + years,
((fromDate.month + months - 1) % DateTime.monthsPerYear) + 1) +
endDate.day -
fromDate.day;
} else {
days = endDate.day - fromDate.day;
}
} else {
months = (endDate.month - fromDate.month);
if (fromDate.day > endDate.day) {
months--;
days = daysInMonth(fromDate.year + years, (fromDate.month + months)) +
endDate.day -
fromDate.day;
} else {
days = endDate.day - fromDate.day;
}
}
return AgeDuration(days: days, months: months, years: years);
}