convertDaysToYearsAndMonths static method
Function to convert an integer representing days into a string format of years and months.
@param days - The number of days as an integer. @return A string in the format of "X year(s) and Y month(s)".
Implementation
static String? convertDaysToYearsAndMonths(int? days) {
if (days == null || days < 1) {
return null;
}
// Calculate the number of years by integer division of the days by 365.
final int years = days ~/ 365;
// Calculate the remaining number of months by first getting the
// remainder of days when divided by 365 (which gives the number of
// days in the current year), then doing integer division by 30.
final int months = (days % 365) ~/ 30;
// Determine whether to use singular or plural form for "year" and
// "month".
final String yearStr = (years == 1) ? 'year' : 'years';
final String monthStr = (months == 1) ? 'month' : 'months';
// Construct the result string.
if (years > 0 && months > 0) {
return '$years $yearStr and $months $monthStr';
} else if (years > 0) {
return '$years $yearStr';
} else if (months > 0) {
return '$months $monthStr';
} else {
return '0 days';
}
}