{

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: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example