The Answer might be a little long but will give you what you need.
This will give you the values as a String in the format "Year : year, Months: month, Days: days". You can change it according to your need.
You need to call differenceInYearsMonthsAndDays() and pass the startDate and endDate.
An Extension to calculate the differents in Months discarding the excess days.
extension DateTimeUtils on DateTime {
int differenceInMonths(DateTime other) {
if (isAfter(other)) {
if (year > other.year) {
if (day >= other.day) {
return (12 + month) - other.month;
} else {
return (12 + month - 1) - other.month;
}
} else {
if (day >= other.day) {
return month - other.month;
} else {
return month - 1 - other.month;
}
}
} else {
return 0;
}
}
}
A Method to generate the Year, Month and Day Format
String differenceInYearsMonthsAndDays(
DateTime startDate,
DateTime endDate,
) {
int days;
final newStartDate = startDate.add(const Duration(days: -1));
int months = endDate.differenceInMonths(newStartDate);
if(months >= 12) {
final years = months ~/ 12;
final differenceInMonthsAndDays = differenceInMonthsAndDays(
startDate.add(const Duration(year: years),
endDate,
);
return "Years : years, $differenceInMonthsAndDays";
} else {
return differenceInMonthsAndDays(
startDate,
endDate,
);
}
}
A Method to generate the Month and Day Format
String differenceInMonthsAndDays(
DateTime startDate,
DateTime endDate,
) {
int days;
final newStartDate = startDate.add(const Duration(days: -1));
int months = endDate.differenceInMonths(newStartDate);
if (months > 0) {
final tempDate = DateTime(
newStartDate.year,
newStartDate.month + months,
newStartDate.day,
);
days = endDate.difference(tempDate).inDays;
return days > 0
? "Months : $months, Days : $days"
: "Months : $months";
} else {
days = endDate.difference(newStartDate).inDays;
return "Days : $days";
}
}