Dart datetime difference in weeks, month and years

2,522

Solution 1

I constructed a package to help me with this called Jiffy

Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.DAY); // -616
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.WEEK); // -88
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.MONTH; // -20
Jiffy([2018, 1, 29]).diff(Jiffy([2019, 10, 7]), Units.YEAR); // -1

Solution 2

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.

Share:
2,522
Jama Mohamed
Author by

Jama Mohamed

Updated on December 14, 2022

Comments

  • Jama Mohamed
    Jama Mohamed over 1 year

    I was working on a project and wanted to add the difference in DateTime in terms of minutes, hours, days, weeks, months and years. I was able to get in minutes up to days. e.g.

    DateTime.now().difference(DateTime(2019, 10, 7)).inDays
    

    But I had a hard time creating it for weeks, months and years. How can I do so, please help