There is a very simple and easy way to do this, and requires very little date/time arithmetic knowledge.
Simply compare both DateTimes' microsecondSinceEpoch values:
Duration compare(DateTime x, DateTime y) {
return Duration(microseconds: (x.microsecondsSinceEpoch - y.microsecondsSinceEpoch).abs())
}
DateTime x = DateTime.now()
DateTime y = DateTime(1994, 11, 1, 6, 55, 34);
Duration diff = compare(x,y);
print(diff.inDays);
print(diff.inHours);
print(diff.inMinutes);
print(diff.inSeconds);
The code above works, and works much more efficiently than conducting checks for leap-years and aberrational time-based anomalies.
To get larger units, we can just approximate. Most end-users are satisfied with a general approximation of this sort:
Weeks: divide days by 7 and round.
Months: divide days by 30.44 and round; if < 1, display months instead.
Years: divide days by 365.25 and floor, and also display months modulo 12.
_daysInMonthArray = [0,31,28,31,30,31,30,31,31,30,31,30,31];
where array 1 is Jan – Dambro