{

How to Find the number of days and years between two dates Dart or Flutter | Dart by Example


 number of days and years between two dates  Dart or Flutter

This tutorial shows multiple ways to find the number of days between two dates.

  • The difference between the DateTime object is using the Duration difference method, Duration.inHours is also used to find the difference between two dates in the number of hours.
  • Find the Number of years between dates

How to find the number of days between two dates in dart

First Created two dates with the DateTime constructor and now() Next, find the difference between two dates using the difference() method. It returns the Duration object which returns the number of days using the inDays property.

Syntax

Duration difference(DateTime other)

Similarly, you can call Duration.inHours to return the number of hours and divide by 24 to get the days to count.

Here is an example program to find differences in days between two dates.

void main() {
  final date1 = DateTime(1990, 03, 03);
  final date2 = DateTime.now();
  final differenceDays = date2.difference(date1).inDays;
  final differenceDays1= (date2.difference(date1).inHours/24).round();

  print(differenceDays);
  print(differenceDays1);

}

Output:

11724
11724

How to find the number of years between two dates in dart

To get the number of years counted between two dates, you can use inDays divided by 365.

void main() {
  final date1 = DateTime(1990, 03, 03);
  final date2 = DateTime.now();
  final differenceDays = date2.difference(date1).inDays;
  final differenceDays1 = (date2.difference(date1).inHours / 24).round();
  final differenceYears = (date2.difference(date1).inDays / 365).floor();

  print(differenceDays);
  print(differenceDays1);
  print(differenceYears);
}

Output:

32

Conclusion

Learn how to find the count of days and years between two dates.

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart