getValidYears method
Get valid years from _years, which is the list of possible years
filtered using the other parameters passed.
For example:
With default allowPastDates, startYear as 2024,
endYear as 2026, and months as 1, 2.
The _years would be 2024, 2025, 2026, and _months would be 1, 2.
These are possible values.
Now, since allowPastDates is false by default. 2024 isn't a valid year,
since months 1 and 2 have already passed. Hence, valid years would only
be 2025, 2026.
Similarly, if days were passed as 1, 3, and since current month is
december, the dates 1 and 2 would not come again.
And moreover, further units can also be taken in but the method does not as it can be unnecessary.
To handle that, the getValidDays method does not include the current day, hence hours, minutes, etc will not be last intances. (Unless it is the last day of year).
Implementation
List<int> getValidYears() {
final List<int> result = _years.where((int year) {
// If the year is in the future, it is valid
if (year > _now.year || allowPastDates) {
return true;
}
// If the year is the current year, we need to check for valid months
// and days. Because if an year is chosen but does not has valid months
// in it. That would backfire.
if (year == _now.year) {
final bool hasValidMonth =
_months.any((int month) => month >= _now.month);
final bool hasValidDay = _days.any((int day) => day > _now.day);
// A year is valid if any of the time units (month, day, hour, minute)
// conditions are met
return hasValidMonth && hasValidDay;
}
// If the year is in the past, it is not valid unless allowPastDates is
// true
return false;
}).toList();
if (result.isEmpty) {
throw ArgumentError('''
Could not generate random dateTime | No valid years found
Most probable cause is that only current year is applicable while
all the months and days have passed. Check the parameters.
''');
}
return result;
}