{

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 difference of two DateTime, return Duration Object. Next, call inDays of Duration object return integer contains 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 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 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example