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

In this tutorial, We will see how to get several days between two dates in Flutter programming. To calculate the number of days between two days, We can use the difference of the DateTime object and call the Duration.inDays method

Sometimes, We need to calculate the number of days between the date of birth and the current date.

Number of Days between two Dates using DateTime.Difference() method

Two DateTime variables are created, one is the date of birth, other is the current Date using DateTime.now(). DateTime.difference() method returns the difference of two DateTime, return Duration Object. Next, call inDays of the Duration object return integer containing several days.

Here is an example code

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

The only drawback is, It takes local time and does return the count. If you want an exact count, input and considered UTC dates with DateTime.utc

How to Calculate the Number of days using Jiffy package in Dart?

Jiffy is a custom package similar to MomenJS in javascript and inspired by it.

It provides many utilities for the manipulation of Date and time 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
  • used Jiffy diff method with Units.DAY measurement
  • It returns an integer that contains the count of days