Dart datetime difference in weeks, month and years
I constructed a package to help me with this called Jiffy
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.DAY); // -616Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.WEEK); // -88Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.MONTH; // -20Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.YEAR); // -1
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.