Dart datetime difference in weeks, month and years

Viewed 3594

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

3 Answers

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

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.

you can calculate month diff size manually (without use any packege):

      static int getMonthSizeBetweenDates(DateTime initialDate, DateTime endDate){
    return calculateMonthSize(endDate)-calculateMonthSize(initialDate)+1;
  }

  static int calculateMonthSize(DateTime dateTime){
    return dateTime.year*12+dateTime.month;
  }

getMonthSizeBetweenDates method gives you how many months between your initial and end dates. for example : your initial date is 1.1.2022 and your end date is 1.3.2022 . then this method return 3 (january, fabruary and march)

You can find week and year diff bye using this logic.

Another method:

static int getMonthSizeBetweenDates2(DateTime initialDate, DateTime endDate){
    return (endDate.year-initialDate.year)*12+(endDate.month-initialDate.month)+1;
  }
Related