Find the number of days between two dates in dart?| Flutter By Example

In this tutorial, we will explore how to calculate the number of days between two dates in Flutter programming. To accomplish this task, we can leverage the difference method of the DateTime object and subsequently call the Duration.inDays method.

Often, we may find it necessary to determine the number of days between a person’s date of birth and the current date.

Number of Days between Two Dates using DateTime’s Difference() Method

We create two DateTime variables: one representing the date of birth and the other representing the current date obtained using DateTime.now().

The DateTime.difference() method calculates the difference between the two DateTime objects and returns a Duration object. Subsequently, calling inDays on the Duration object yields an integer representing the number of days.

Here’s an example code snippet:

void main() {
  var dateOfBirth = DateTime(1980, 01, 10);
  var currentDate = DateTime.now();
  var different = currentDate.difference(dateOfBirth).inDays;
  print(different); //15397
}

The method has a limitation: it considers local time and returns the count accordingly. For an exact count, it’s recommended to provide and consider UTC dates using DateTime.utc.

How to Calculate the Number of Days using the Jiffy Package in Dart?

Jiffy is a custom package similar to MomentJS in JavaScript and draws inspiration from it. It offers various utilities for manipulating dates and times in Dart programming.

void main() {
  var dateOfBirth = DateTime(1980, 01, 10);
  var currentDate = DateTime.now();
  var daysCount=Jiffy(currentDate).diff(dateOfBirth, Units.DAY); // 15397
  print(daysCount); //15397
}
  • Two DateTime objects are created.
  • The Jiffy diff method is employed with the Units.DAY measurement.
  • It returns an integer containing the count of days.